In its simplest form, you can render multiple components by mapping over an array of data. Each array element can be used to render a corresponding component.
// Define a component function NumberList(props) { const numbers = props.numbers; // Create a list of components from an array const listItems = numbers.map((number) => <li>{number}</li> // Each number in the array is used to create an <li> element. ); return ( <ul>{listItems}</ul> // The array of <li> elements is rendered inside an <ul> element. ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, // Pass the 'numbers' array as a prop to the NumberList component. document.getElementById('root') );
In this example, the NumberList
component receives an array of numbers as a prop and creates an <li>
element for each number.
To give each list item a unique identity, you should assign a key to each item. This will help React optimize re-rendering when the list changes.
function NumberList(props) { const numbers = props.numbers; // Create a list of components with unique keys const listItems = numbers.map((number) => <li key={number.toString()}> // Each number in the array is used to create an <li> element with a unique key. {number} </li> ); return ( <ul>{listItems}</ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
In this intermediate example, each <li>
element gets a unique key
prop. This key helps React identify which items have changed when the list is modified.
When dealing with complex objects and more components, it’s often beneficial to extract components for readability and maintainability. You should also keep the keys on the outermost component being added in the array.
// Define a component for a list item function ListItem(props) { // There's no need to specify the key here: return <li>{props.value}</li>; } // Define a component for the whole list function NumberList(props) { const numbers = props.numbers; // Create a list of ListItem components const listItems = numbers.map((number) => // The key should be specified on the enclosing tag (<ListItem />) in the array. <ListItem key={number.toString()} value={number} /> // Each number in the array is used to create a ListItem component with a unique key. ); return ( <ul>{listItems}</ul> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('root') );
I
n this advanced example, the NumberList
component creates an array of ListItem
components. Each ListItem
component receives a unique key and the number to be displayed.