Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js pass object key-value pairs as props

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.

like image 780
eye_mew Avatar asked Nov 19 '14 04:11

eye_mew


People also ask

Can you pass object 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.

How do you pass an array of objects as a prop in React?

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.

How we are able to extract the key value pairs from props React?

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.

How do you map a key value pair in React?

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.


1 Answers

With React 0.12 and a recent jsx version you can use the spread operator.

<MyReactElement foo={bar} {...myObject} />
like image 72
Brigand Avatar answered Oct 12 '22 14:10

Brigand