41

I am very new to react and all I really want is a simple for loop that creates menuitem elements for each user in my array with the title of it being their firstname. So this is how I would write it, but I have no clue of how to do this in react. I think it should be with a map maybe but I cant seem to get it to work either hopefully anyone out here can help me.

for (var i = 0; i < Users.length; i++) {
  <MenuItem eventKey=[i]>User.firstname[i]</MenuItem>
}
peterh
  • 11,875
  • 18
  • 85
  • 108
novafluff
  • 891
  • 1
  • 12
  • 30
  • 1
    You can't iterate within JSX elements with `for` loop. use [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instead. – Mostafiz Rahman Jan 17 '18 at 14:15
  • @MostafizRahman is correct. A react component expects either a string, another component, or an array of components. For loops do not return any of these. This is why we have to store the value of the for loop in a variable and return the variable. See [How To Loop Inside React JSX - React FAQ](https://victorofoegbu.com/notes/loop-inside-react-jsx-faq) or this [answer](https://stackoverflow.com/a/22877049/8828126) – Victor Ofoegbu May 25 '21 at 03:42

2 Answers2

51

The render method of your component, or your stateless component function, returns the elements to be rendered.

If you want to use a loop, that's fine:

render() {
    let menuItems = [];
    for (var i = 0; i < Users.length; i++) {
        menuItems.push(<MenuItem eventKey=[i]>User.firstname[i]</MenuItem>);
    }
    return <div>{menuItems}</div>;
}

More common would be to see a more functional style, such as using a map to return the array of elements:

render() {
    return <div>
    {
        Users.map((user, i) =>
            <MenuItem eventKey=[i]>User.firstname[i]</MenuItem>)
    }
    </div>;
}

Note that in either case, you are missing the key property from each element of your array, so you will see warnings. Each element in an array should have a unique key, preferably some form of ID rather than just the array index.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
9

With map you can do:

Users.map((user, index) => (
  <MenuItem eventKey={index}>user.firstname</MenuItem>
));
Mostafiz Rahman
  • 8,169
  • 7
  • 57
  • 74
RMontes13
  • 2,138
  • 3
  • 16
  • 23