ABGR
ABGR

Reputation: 5235

Please explain the use of spread operator in this case

I have just started with reactjs and I came across this snippet while working on react databatle:

class MyTextCell extends React.Component {
  render() {
    const {rowIndex, field, data, ...props} = this.props;
    return (
      <Cell {...props}>
        {data[rowIndex][field]}
      </Cell>
    );
  }
}

My questions are following:

  1. const {rowIndex, field, data, ...props} = this.props;

As far as I understand this can be interpreted as

rowIndex= this.props.rowIndex
 field= this.props.field

and ...props will make sure it gets all the objects of this.props EXCLUDING rowIndex, field and data. Am I correct?

So my question is, isn't it would be better if instead of ...props say, ...somethingElse would have been used in order to make both 'props' look different.

  1. In <Cell {...props}> what does ...props actually contain? All the objects of this.props or the 'remaining' ones other than rowIndex, field, data etc?

This is the link from where the snippet is taken: https://facebook.github.io/fixed-data-table/getting-started.html

Upvotes: 2

Views: 197

Answers (1)

ctrlplusb
ctrlplusb

Reputation: 13147

1. const {rowIndex, field, data, ...props} = this.props;

This is an implementation of an ES6/2015 feature and a proposed feature:

So to explain it clearly, the this.props object is being "destructured" into 4 new properties, namely rowIndex, field, data, and props. With the props argument being the result of the "object rest" which gathers all the additional properties and puts them into a new object.

Therefore, your assumption for no 1 is correct. ...props will indeed contain all props other than rowIndex, field, and data. The great thing about this is that you didn't need to know of or list out any of the "other" properties, they will be automatically bound into the newly created props object.

It's completely up to you on how you would like to name this, but I agree that "reusing" the name props may be a bit confusing. Take it on a case by case basis. I tend to name mine differently.

2. <Cell {...props}>

This is an implementation of the "JSX spread attributes" syntax (https://facebook.github.io/react/docs/jsx-spread.html).

This will take all the properties in an object and then spread them over the target JSX node.

So for example if you had incoming props object of:

{ rowIndex: 1, field: 'foo', data: 'bar', message: 'hello', name: 'Bob' }

That would result in:

<Cell message="hello" name="bob" />

This kind of thing is really useful for when you create higher order components that wrap a component, but you don't want the higher order component specific props to be passed into the wrapped component.

Upvotes: 3

Related Questions