Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop inside React JSX

I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):

<tbody>     for (var i=0; i < numrows; i++) {         <ObjectRow/>     }  </tbody> 

I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).

like image 621
B Robster Avatar asked Apr 05 '14 05:04

B Robster


People also ask

Can we use for loop inside JSX in React?

Two Ways to Loop Inside React JSXWe can build a loop and add a JSX element to an array using the for a loop. elements. push(): To insert one or more values into the array, use the arr.

Can we write for loop in React?

Although we can write a for loop in React, ES6 provides the more appropriate map function for us to use.

How do I use htmlFor in React?

In class-based components, the htmlFor attribute is used to get the HTML for the given HTML elements. Creating React Application And Installing Module: Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. foldername, move to it using the following command.


2 Answers

I am not sure if this will work for your situation, but often map is a good answer.

If this was your code with the for loop:

<tbody>     for (var i=0; i < objects.length; i++) {         <ObjectRow obj={objects[i]} key={i}>     } </tbody> 

You could write it like this with map:

<tbody>     {objects.map(function(object, i){         return <ObjectRow obj={object} key={i} />;     })} </tbody> 

ES6 syntax:

<tbody>     {objects.map((object, i) => <ObjectRow obj={object} key={i} />)} </tbody> 
like image 27
Brigand Avatar answered Sep 21 '22 13:09

Brigand


Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:

return tbody(     for (var i = 0; i < numrows; i++) {         ObjectRow()     }  ) 

See how the function tbody is being passed a for loop as an argument – leading to a syntax error.

But you can make an array, and then pass that in as an argument:

var rows = []; for (var i = 0; i < numrows; i++) {     rows.push(ObjectRow()); } return tbody(rows); 

You can basically use the same structure when working with JSX:

var rows = []; for (var i = 0; i < numrows; i++) {     // note: we are adding a key prop here to allow react to uniquely identify each     // element in this array. see: https://reactjs.org/docs/lists-and-keys.html     rows.push(<ObjectRow key={i} />); } return <tbody>{rows}</tbody>; 

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

like image 137
Sophie Alpert Avatar answered Sep 20 '22 13:09

Sophie Alpert