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?
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} />
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