Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Spread Component Props in JSX with React

    John LindquistJohn Lindquist

    You often find duplication between the name of a prop and a variable you will assign to the prop. JSX allows you to spread an object containing your named props into your Component which enables you to avoid the repetition of matching prop names and variable names. This lessons covers spreading JSX component props in both pure components and class components.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: It's a fairly common scenario to have a component which takes some props. When you go to define it -- let us create our new component -- you have those props.

    You just assign them to the same exact name, so name and name there where the greeting is the same name as the variably you're passing in. The name variable's the same as the prop up there, so there's a bit of duplication going on here.

    What you can actually do to avoid some characters there is just to use the curly braces, without defining a prop name, and then write another object inside of there and spread that object. This looks like this greeting and name.

    You see that works the exact same way, where this is an object that's just being spread out across the named props of the demo.

    You could actually change the way you think about this if this looks confusing. I'm just going to invoke my demo function with an object and hit save.

    You see this is the same result, because it's just demo taking an object where the props are named the same as these variables up here. The JSX syntax to accomplish that is again demo, the curly braces, and then you spread an object with those names.

    Now, this looks a little bit different with classes, class demo extend React.Component. Then, I render out in my render method, and I return an H2 with this.props.greeting and this.props.name. I'll hit save and everything works the same.

    Now, the equivalent of JavaScript is a little bit different, because this no longer works where you do invoking a function and passing an object.

    This is a class, so you think maybe I can do new demo. That also doesn't work, because what you need to do is use React.createElement. Then the demo is the type, and the props are the second parameter there. You can see now it's back to the way it was.

    This object, whether it's through createElement or invoking a function for a peer component, is the equivalent in JSX to using JSX writing those curly braces without a prop name, then passing an object in and spreading it.