Pass an Array as prop to a component in React.js

avatar

Borislav Hadzhiev

Last updated: Apr 5, 2022

banner

Photo from Unsplash

Pass an Array as prop to a component in React.js #

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.

App.js
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.

The prop we passed to the 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.

App.js
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 above achieves the same result as the previous one.

If you iterate over the array, make sure to set a unique key prop on each element.

This is necessary because it helps React keep track of which array elements changed between re-renders and React is able to make our applications faster by just updating the array elements that changed.

You can also pass individual array elements as props to a component.

App.js
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.