How to loop in React JSX?

Today, we will look at how to loop over and render a component in React.

Full Transcript

Today, we look at how to loop over and render a component in react. I'm writing this code in codesandbox, and the link is in the description. If you need access to the code, check out the description below. Let's say we have a variable cars whose value is an array of strings. There are nothing but the name of different cars. Our goal is to render each car name in a row. So first thing we would do is below the header component, we will iterate over every element inside the cars array using map() function. For each car and a key, we return a div pass the key prop to the div element and then call a Car component. We pass to the prop name, the value of the car.

Now we are wrapping the Car component inside a div element, but you may directly call the Car component too. Often, you will return a separate component when you loop over. So let's go ahead and write this Car component. It's a function component which returns a div that display the name of the car. The car name will be passed by the caller and we can style it a little bit with borders, say 1 pixel solid gray. And there you go! For each element in cars array, you're able to render a Car component. Now, a few things to notice here when you iterate over objects and render a component, react requires you to give a unique key so that it can identify each item in the collection. For the purposes of this example, I simply used key, which will default to index of each car name in the array as a key. This is react default, but you can always change it and give another unique ID. If you don't give one, you will see the warnings on the console. Next, do not forget the return statement when you map over the elements in an array, your goal is to return the element on every iteration and that's it. I hope it was useful for you.

Thanks for watching.