How you can create a list of items with ReactJS
In React, you render lists with some type of loop. The JavaScript map()
array method is generally the preferred method.
Code Sample:
unction Car(props) {
return <li>I am a { props.brand }</li>;
}
function Garage() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car brand={car} />)}
</ul>
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
Note: When you run the code above in your create-react-app
, it will work, but you will receive a warning that there is no "key" provided for the list items.
I guess you might be confused by what I mean with the word key
. Now let me explain what key is in React:
Keys allow React to keep track of elements. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list. Keys need to be unique to each sibling. But they can be duplicated globally. Mainly, the key should be a unique ID assigned to each item. As a last resort, you can use the array index as a key.
Now you should have the basic understand of what "key" is all about, now let me show a code sample for better explanation. Now let's refactor the sample above by adding key to our code:
function Car(props) {
return <li>I am a { props.brand }</li>;
}
function Garage() {
const cars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car key={car.id} brand={car.brand} />)}
</ul>
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
We can also say that the main purpose of keys is to help React differentiate and distinguish elements from each other, increasing its performance when diffing between the virtual and real DOM.
For now, I'm going to be writing some short tutorials, and grouping it section by section next I will discuss How to create a form with ReactJS.
I really appreciate those that are dropping messages to my social handles. I will try my best to always publish all answers to your questions here on my blog.
Always remember this my common quote:
Never give up on your dreams, always stay motivated and don't get distracted by your environment and bad situations. You will surely make it if you don't give up.