DEV Community

Cover image for How to enact a Component Loop in React ⚛️
Hitesh Chauhan
Hitesh Chauhan

Posted on • Updated on

How to enact a Component Loop in React ⚛️

Do you know that you can write Javascript code within your components with the help of React? Moreover, you might also be aware that when react allows you to write javascript code, it makes programming approaches simple for the react js developer. We have penned down the techniques here: looping through a list of objects, generating and executing functions, saving data in local variables, and so on. This tutorial shows how to use loops in basic scenarios like showing a list of static data and displaying data from an API.

👉OutPut Arrays in JSX

Do you have any idea What are these component loops? Component Loops are the normal JavaScript loops that are further combined with some JSX. The ability to output arrays directly on the DOM is a fantastic feature of JSX. So, if you have a data array, you may use the DOM to display its elements, as demonstrated below:

1  return(
2     <>
3     {data}
4      </>
5  )
Enter fullscreen mode Exit fullscreen mode

As a result, you can push your data with supporting HTML into an array and output that array using curly braces in your component's return statement. However, you can accomplish this with a variety of JavaScript loops. Because map() is the most popular and straightforward, it is used extensively in the examples in this article.

👉Static Data Rendering

Consider the following scenario: you need to render a list of things on the DOM.

import react from react

As illustrated above, rendering each <li> would be inconvenient and time-consuming. the best approach is to break out the recurring segment of your code and push it into an array. Each <li> tag, for example, can be viewed as a repeating segment, allowing you to generate an array with the following data:

1 let items=['Item=1','Item=2','Item=3','Item=4'];
Enter fullscreen mode Exit fullscreen mode

Eventually, the output of this array will look like this:

Image djackson

Additionally, by pushing the whole HTML in an array, you can clean up your JSX:

Image react js developers

After it, you need to render that single array

Image Hire react.js developers

On second thought, you can also do the same by using the forEach() method, as displayed below:

Image 5

Moreover, you can examine the above method by using a regular for loop, and it will work in the same way. Indeed, when the components grow larger in size, the segmenting code away from your UI will make it more clean, compatible, and readable. So, it is easy to do the debug.

👉Dynamic Data Rendering

In a real-world scenario, you'd normally obtain data from a backend, save it in your component's state, and then loop over it to display it on the page. Even the professionals of the react js development company perform the same task. Consider the following scenario: you want to get a list of users for your web app.
Create a simple state variable to hold an array of objects by importing useState.

Image 6

Moreover, you can install Axios to make API calls by executing the following command in the root directory:

1 npm install axios`
Enter fullscreen mode Exit fullscreen mode

After it requests on the front end, the page should load fully with the data. The data must be populated when the component mounts for the first time on the DOM. Moreover, by sending an empty as a second parameter, you can accomplish it with the help of lifecycle hook useEffect().

Image react js development company

Following, populate the condition of the date from your server.

Image react js

By using map(), the expert react js developers can cycle through the data and show it on the page.

Image react js development

At last, the professionals can separate the logic from the template.

Image hire react js developer

Sum up

Hence, the use of components loops for the output and manipulating the data is the standard development method in React. As explained in this guide, it allows you to group HTML components with dynamic data together. However, it is challenging to achieve in a pure JavaScript app without DOM queries. So, the component loops are used to output sets of objects in a clean, efficient, and readable way.

Discussion (4)

lukeshiru profile image
Luke Shiru

A few observations:

  • Ideally you should avoid using index as a key, unless you're actually planning on always showing the same amount of elements statically without any updates. This is because if you update that array new elements might have the same index old items had. Let's say you have ["a", "b", "c"], so the key for "a" is 0, for "b" is 1 and for "c" is 2. Now let's say we remove "b", the key for "c" will be 1 now, which produces rendering errors in React. Try using a unique identifier instead.
  • You should avoid doing the forEach approach you suggested, keep it simple by just using a map. If you don't want to inline that map, you don't have to, you can just assign it's output to a constant and use that in JSX.
  • You don't need axios for something as simple as this, you can just use fetch:
    () =>
        void fetch("")
            .then(response => response.json())
            .then(({ data }) => setUserData(data))
Enter fullscreen mode Exit fullscreen mode
  • In DEV you can (and ideally should) share code snippets in text form instead of screenshots. These are more accessible and better for mobile devices. You can achieve this using a triple back-tick followed by the language (this time jsx) and then other triple back-tick to close it. Yo can see more details here.
  • Las thing: you don't need return in arrow functions with a single statement, here's your last example without it:
const users =
    userData?.map(({ id, email, first_name, last_name }) => (
        <li key={id}>
                {first_name} {last_name}
    )) ?? "No users";

return <ul>{users}</ul>;
Enter fullscreen mode Exit fullscreen mode

You can see we used id for the key, which should be unique, and we also did a slight change in the html to make it more "semantic".


hiteshtech profile image
Hitesh Chauhan Author

Agree with your first point. We could avoid using index as a key.
You've explain well. Good job buddy! 👍

lico profile image
SeongKuk Han

I'm used to render an array with map right away in 'return'. I thought it wouldn't be good tho it didn't come up on my head while working. Your post made me to remind that. Seperating the logic and using useMemo would be better. Thanks for sharing :)

hiteshtech profile image
Hitesh Chauhan Author

Glad you find my post valuable.