Using for loops in react.js

Hello everyone!

I’m trying to use ‘for loops’ instead of .map function but it’s not working.
Here is what I’m trying to do

import React from 'react';
import ReactDOM from 'react-dom';

const people = ['Rowe', 'Prevost', 'Gare'];

const peopleLis = for(var i = 0; i < people.length; i++){
  return <li>{people[i]}</li>
}
// ReactDOM.render goes here:
ReactDOM.render(
<ul>{peopleLis}</ul>,
document.getElementById('app')
);

Here is the original solution code.

import React from 'react';
import ReactDOM from 'react-dom';

const people = ['Rowe', 'Prevost', 'Gare'];

const peopleLis = people.map(person =>
  // expression goes here:
<li>{person}</li>
);

// ReactDOM.render goes here:
ReactDOM.render(
<ul>{peopleLis}</ul>,
document.getElementById('app')
)

When I clicked run, it doesn’t produce the same result. What is wrong with my for loop?

return can only be used inside a function or method, which you do not have if you use a for loop.

1 Like

what should i use instead of return?

its not that simple, we are dealing with react components. You could make separate components. But using .map() is better and easier

2 Likes

Hey Scriptmaster, there’s almost no reason to use a for loop, you’re way better off with using .map.

Is there a reason you wanted to use for?

1 Like

And honestly, Just for fun i gave it a go.

const people = ["Rowe", "Prevost", "Gare"];
let peopleToReturn = [];

const peopleLis = () => {
  for (let i = 0; i < people.length; i++) {
    peopleToReturn.push(<li> {people[i]}</li>);
  }
  return peopleToReturn;
};

// ReactDOM.render goes here:
ReactDOM.render(<ul>{peopleLis()}</ul>, document.getElementById("app"));

Basically I put the for loop inside a function, looped over your array and inserted the names into a new array then returned the new array with the list tags…
This is not recommended at all!

Use .map

@derknez Yes, I just wanted to try out how to do this using for loop instead of .map function.

Thank you for giving it a go, So the .push method is the key here. Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.