How can I pass an array to a component as a property. Neither of the following achieve what I am looking for. I want to pass the array of items through, manipulate them in the component and output in the render method.
<List columns=['one', 'two', 'three', 'four'] /> // unexpected token
<List columns="['one', 'two', 'three', 'four']" /> // passed through as string not array
Is there a standard syntax or best practice for this kind of thing?
As you all know, properties which are shortly called as props is one of fundamental blocks of React. Props will allow you to pass the parameters between the components, they could be strings, numbers, object or arrays. Here is the simple example of using the props.
To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.
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. Copied!
You need to use {}
around js expressions:
<List columns={['one', 'two', 'three', 'four']} />
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