Last updated: Jan 15, 2023
Reading timeยท2 min
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.
function Books({arr}) { console.log(arr); // ๐๏ธ ['A', 'B', 'C', 'D'] return ( <div> {arr.map(title => { return <div key={title}>{title}</div>; })} </div> ); } export default function App() { const arr = ['A', 'B', 'C', 'D']; return ( <div> <Books arr={arr} /> </div> ); }
When passing any prop other than a string to a React component, we have to wrap the value in curly braces.
The curly braces mark the beginning of the expression.
Books
component is called arr
, so the component can destructure the prop and perform logic on it or use the Array.map()
method to render its elements.You can also pass the array prop to the component inline.
function Books({arr}) { console.log(arr); // ๐๏ธ ['A', 'B', 'C', 'D'] return ( <div> {arr.map(title => { return <div key={title}>{title}</div>; })} </div> ); } export default function App() { return ( <div> <Books arr={['A', 'B', 'C', 'D']} /> </div> ); }
The code snippet achieves the same result.
If you need to pass an object as props, click on the link and follow the instructions.
If you iterate over the array, make sure to
set a unique key
prop on each element.
When adding a key prop to a React Fragment, make sure to use the verbose syntax.
Note that you shouldn't try to access the key
property, otherwise, the warning
Key is not a prop. Trying to access it will result in undefined
is raised.
You can also pass individual array elements as props to a component.
function Books({first, second}) { console.log(first); // ๐๏ธ 'A' console.log(second); // ๐๏ธ 'B' return ( <div> {first} {second} </div> ); } export default function App() { const arr = ['A', 'B', 'C', 'D']; return ( <div> <Books first={arr[0]} second={arr[1]} /> </div> ); }
We are able to pass individual array elements as props to a component by accessing the array element at the specific index.
If you need to check if a prop is passed to a component, click on the following article.
You can learn more about the related topics by checking out the following tutorials: