The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Compose React Component Behavior with Higher Order Components

Compose React Component Behavior with Higher Order Components

4:05
Higher order components will allow you to apply behaviors to multiple React components. This can be done by passing the state and any functions into components as props.
Watch this lesson now
Avatar
egghead.io

Higher order components will allow you to apply behaviors to multiple React components.

Avatar
Jin

it'd be cool if you can explain a bit more on the spread operator, had a look at react's doc, was not very clear

Avatar
Jay Looney

The spread operator is an ES6 feature, not a React feature. It's a direct way to access a collection as an iterable. So if you had an array like let myArray = [0, 1, 2, 3] you can access every element with the spread operator. console.log(...myArray) would output 0 1 2 3. Math.max(...myArray) would output 3. Please let me know if my explanation was any good.

In reply to Jin
Avatar
Felix

I also do not understand the use of the spread operator in there.
how does this translate into an components attribute if these are basically just values?

Does

return <InnerComponent
      {...this.state}
     />

becomes to something like

<InnerComponent val="3"/>

?

Avatar
Joseph

Exactly. You could achieve the same thing like this:

return <InnerComponent val={this.state.val} txt={this.props.txt}   />
In reply to Felix
Avatar
Zhenyang Hua

what if the component has a state called "val": this.state = {val: '0'}, and also has a prop called "val": this.props.val = '1'. Is React smart enough to carry over same name state and props when using spread operator?

In reply to Joseph
Avatar
Joseph

No, React is not going to differentiate between two values for 'val' passed into a components props. This is not a React-specific issue, it's just something you shouldn't do in JS in general. The outcome will be that the last one passed in will win.

In reply to Zhenyang Hua
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?