React - Transferring props shorthand

Is there a more succinct way to write this? I feel like I’m repeating myself a lot.

<MyComponent
   tip={this.props.tip}
   options={this.props.options}
   anonymous={this.props.anonymous}
   order={this.props.order}
   numOfDecisions={this.props.numOfDecisions}
   decisionId={this.props.decisionId}
   expertSessionId={this.props.expertSessionId}
/>
1 Like

Yes you can spread props {...this.props}

5 Likes

Yep, what Abhi said. Also, keep in mind you can exclude certain props from being passed in… for example:

  const {
    useThese,
    properties,
    locallyOnly,
    ...others,
  } = this.props;
  
  {/* useThese, properties, and locallyOnly will not be passed into MyComponent */}
  return <MyComponent { ...others } />
4 Likes

You can destructure this.props to get variables and then use the shorthand object syntax to create a new object to pass in with the spread syntax. This keeps things very clear as to what is going into the component without searching.

const {tip, options, anonymous, order, numOfDecisions, decisionId, expertSessionId} = this.props;
const myProps = {tip, options, anonymous, order, numOfDecisions, decisionId, expertSessionId};
<MyComponent {...myProps} />

As suggested you can just do <MyComponent {...this.props} /> but it comes at a maintenance cost. You no longer know what is being passed in just by looking at it. this.props count contain anything. However, this can be mitigated by using propTypes on MyComponent. Then you just have to open another file to see what’s being passed.

1 Like

Read this: https://facebook.github.io/react/docs/transferring-props.html

Thanks all. Came up with this:

{..._.pick(this.props, ['foo', 'bar', 'baz', 'bat'])}

It’s pretty terse though readability is arguable. You keep control over what props get passed in.

4 Likes

Love it… this is even more readable :thumbsup: