Kylian Murphy Kylian Murphy - 1 month ago 5
React JSX Question

Creating a looped HTML element in React

I'm relatively new to React, I've looked a lot of places and can't find a way to specifically handle this. I have checked previous answers.

I am trying to get my application to loop through an array and also print a statement along with the array.

var user = ["Kevin", "Kyle", "Kylian"];

var Hello = <h1>
Hello, {user}!
</h1>

class App extends Component {
render() {
for(var i=0;i<user.length;i++){
return Hello;
}
}
}

export default App;


Output:

Hello, KevinKyleKylian!


Expected Output:

Hello, Kevin!
Hello, Kyle!
Hello, Kylian!


As you can see, the loop for some reason doesn't continuously return the entire output and after the user iteration of {user} it just prints {user} until the array is ended. Why does this happen? How can I avoid this?

Answer

It's probably because of this bit:

var Hello = <h1>
            Hello, {user}!
            </h1>

In that case 'user' is referring to the whole array, not just a specific element of that array.

Generally, if you're building elements dynamically in React it's good to put that in a separate function rather than the render method, I feel it's a bit neater. So something like this:

getUsers() {
  let userList = [];
  for (let i=0; i<user.length; i++) {
    userList.push(<div>Hello, {user[i]}</div>);
  }
  return userList;
}

render() {
  return(
    <div>
      {this.getUsers();}
    </div>
  );
}