0

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?

1
  • I've also tried return <h1> Hello, {user[i]} </h1> Commented Oct 29, 2016 at 22:43

1 Answer 1

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, this worked. I had to change render() { return( <div> this.getUsers(); </div> ); } to render() { return( <div> {this.getUsers()}; </div> ); }
React is difficult, I'm relatively new and it's just a lot to learn all at once! I did the entire CodeAcademy course and didn't learn a thing. So now I'm doing it again and building an app along side of it as I learn to have a more practical grasp of it.
Yeah React is hard to learn initially, but once things start to click it's super fun and much easier. Just gotta get over that initial learning hump
Yeah, I figured. I think what is most confusing is transitioning from JS to JSX and then also incorporating the React commands as well. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.