I often find myself doing something like this in my jsx:
myObject= {key1 : 'value1', key2 : 'value2'};
var reactElement = <MyReactElement key1={myObject.key1} key2={myObject.key2}/>;
Is any infrastructure provided to allow me to pass all the key value pairs in my object, as props to an element? I'm aware I can pass in the entire object, but it doesn't feel maximally elegant, especially if it's the only thing I'm passing, since I then have to refer to this.props.myObject.key1
.
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.
To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements.
entries() is another way to extract the number of key-value pairs from the props object. Below is some simple syntax. You need to pass the name of the object along with the function Object. entries() , which gets the key-value pair, and afterward you can use those known keys and values as demonstrated below.
To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.
With React 0.12 and a recent jsx version you can use the spread operator.
<MyReactElement foo={bar} {...myObject} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With