Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use for loops with react? [duplicate]

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> } 
like image 945
novafluff Avatar asked Oct 24 '17 10:10

novafluff


People also ask

How do you repeat on React?

To repeat an element n times with React, we can use the Array function with the map array method. to create an array with 8 span elements with the same content by calling the Array with the n to create an empty array with n slots. Then we use the spread operator to make a copy of it.

Can you use for loops in React?

It is very popular to use loops like for-loop (in most cases the fastest one), for-in, or for-of to iterate through elements. That method is useful when we use separate functions to render part of components, and it's the best method for performance.

How do you handle double click in React?

To handle double click events in React:Add an onClick prop to the element. Use the detail property on the event object to get the click count. If the click count is equal to 2, handle the double click event.

How do you repeat an element and time using JSX?

A solution We could use a for loop outside JSX to build the field elements and then output the field elements in JSX: const fields: JSX. Element[] = [];for (let i = 1; i <= committedFieldsToAdd; i++) { fields. push(<Field id={i} key={i} />);} return ( <div> ...


2 Answers

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.

like image 99
Tom Fenech Avatar answered Oct 08 '22 04:10

Tom Fenech


With map you can do:

Users.map((user, index) => (   <MenuItem eventKey={index}>user.firstname</MenuItem> )); 
like image 42
RMontes13 Avatar answered Oct 08 '22 04:10

RMontes13