React Lists
In React, you will render lists using a loop.
The JavaScript map() array technique is often preferable.
If you need a refresher on the map() method, refer to the ES6 section.
Example
Let’s render every vehicle in our garage:
function Car(props) {
return I am a { props.brand } ;
}
function Garage() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<>
Who lives in my garage?
{cars.map((car) => )}
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
This code will function in your create-react-app when you run it, but a warning about the lack of a “key” for the list items will appear.
Keys
Keys enable React to keep track of elements. This manner, if an item is modified or removed, only that item will be re-rendered, not the entire list.
Keys must be unique to each sibling. However, they can be reproduced globally.
In general, the key should be a unique ID for each item. As a final resort, utilize the array index as a key.
Example
Let us rewrite our earlier example to incorporate keys.
function Car(props) {
return I am a { props.brand } ;
}
function Garage() {
const cars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
];
return (
<>
Who lives in my garage?
{cars.map((car) => )}
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
If you want to communicate a variable rather than a string, as in the example above, simply place the variable name inside curly brackets:
Example
Create a variable called carName and pass it to the Car component:
function Car(props) {
return I am a { props.brand }!
;
}
function Garage() {
const carName = "Ford";
return (
<>
Who lives in my garage?
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Alternatively, if it were an object:
Example
Create an object called carInfo and send it to the Car component.
function Car(props) {
return I am a { props.brand.model }!
;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
Who lives in my garage?
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );