Saturday, 19 August 2017

reactjs - How do i use for loops with react?





I'm 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++) {
User.firstname[i]

}

Answer



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(User.firstname[i]);
}
return
{menuItems}
;
}


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



render() {
return


{
Users.map((user, i) =>
User.firstname[i])
}
;
}


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.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...