Respond to shorthand for the passage of props

I am tired of this all the time:

<Elem x={x} y={y} z={z} />
<Elem x={this.props.x} y={this.props.y} z={this.props.z} />

Is there a way I can get something like this to work?

<Elem x, y, z />

or

<Elem {x, y, z} />
+4
source share
3 answers

As pointed out in the comments, you should use the distribution operator as a reduction in sending multiple arguments to the component.

<Elem {...this.props} />

If the Elem component is a stateless component, you must have access to the details just like any argument passed to the component. In this case, you do not have to use a keyword this.props.

+5
source

It should be noted that this only works for objects. eg:

this.props = {
  x: 'foo', 
  y: 'bar',
  z: 'baz',
}

const {
  x,
  ...allOtherProps
} = this.props

<Elem { ...allOtherProps } /> // works (allOtherProps is an object)
<Elem { ...x } /> // does not work (x is not an object)
<Elem x={ x } /> // works
+2
source

, this.props, :

<Elem {...this.props} />

, :

<Elem {...{ x, y, z }} />
+1

Source: https://habr.com/ru/post/1671570/


All Articles