'Is there a React shorthand for passing props?

I am tired of doing 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} />


Solution 1:[1]

As specified in the comments , you should use a spread operator as a shorthand of sending multiple arguments to the component.

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

If the Elem component is a stateless component , you should be able to access the props just like any argument passed on the component. You probably dont need to use the this.props keyword in that case.

Solution 2:[2]

If your variables are contained in an object, such as this.props, you spread the object:

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

Otherwise, you spread a new object containing the variables you need:

{...{ x, y, z }}

Although it creates a new object for no good reason.

Solution 3:[3]

it should be noted that this only works for objects. for example:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kannaj
Solution 2
Solution 3 Ali Torbati