Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an object containing props to React component?

A component with props a and b can be rendered using:

<Component a={4} b={6} />

Can one pass an object instead that contains the props as keys, something like this?

let componentProps = { a: 4, b: 6 }
<Component componentProps />

If so, how?

like image 913
NiloCK Avatar asked May 26 '17 03:05

NiloCK


1 Answers

Sure. Make sure to use spread syntax. Per the React documentation:

Spread Attributes

If you already have props as an object, and you want to pass it in JSX, you can use ... as a "spread" operator to pass the whole props object. These two components are equivalent:

function App1() {
  return <Greeting firstName="Ben" lastName="Hector" />;
}

function App2() {
  const props = {firstName: 'Ben', lastName: 'Hector'};
  return <Greeting {...props} />;
}

Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.

You can use this spread syntax to this situation, because you're "spreading the props to the component". It's applied like so, though use this sparingly:

let componentProps = { a: 4, b: 6 }
<Component {...componentProps} />

The above is equal to passing the props separately:

<Component a={4} b={6} />
like image 158
Andrew Li Avatar answered Sep 28 '22 14:09

Andrew Li