Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a React shorthand for passing props?

Tags:

reactjs

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} /> 
like image 545
andree Avatar asked Mar 06 '17 08:03

andree


People also ask

How do you pass down a prop in React?

export default App; Basically that's how props are passed from component to component in React. As you may have noticed, props are only passed from top to bottom in React application's component hierarchy. There is no way to pass props up to a parent component from a child component.

Can you pass objects as props in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.


1 Answers

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:

<Elem {...{ x, y, z }} /> 
like image 84
Alice Rocheman Avatar answered Sep 20 '22 18:09

Alice Rocheman