[javascript] 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).

This question is related to javascript reactjs jsx

The answer is


When I want to add a certain number of components, I use a helper function.

Define a function that returns JSX:

const myExample = () => {
    let myArray = []
    for(let i = 0; i<5;i++) {
        myArray.push(<MyComponent/>)
    }
    return myArray
}

//... in JSX

<tbody>
    {myExample()}
</tbody>

I tend to favor an approach where programming logic happens outside the return value of render. This helps keep what is actually rendered easy to grok.

So I'd probably do something like:

import _ from 'lodash';

...

const TableBody = ({ objects }) => {
  const objectRows = objects.map(obj => <ObjectRow object={obj} />);      

  return <tbody>{objectRows}</tbody>;
} 

Admittedly this is such a small amount of code that inlining it might work fine.


With time, the language is becoming more mature, and we often stumble upon common problems like this. The problem is to loop a Component 'n' times.

{[...new Array(n)].map((item, index) => <MyComponent key={index} />)}

where, n -is the number of times you want to loop. item will be undefined and index will be as usual. Also, ESLint discourages using an array index as key.

But you have the advantage of not requiring to initialize the array before and most importantly avoiding the for loop...

To avoid the inconvenience of item as undefined you can use an _, so that it will be ignored when linting and won't throw any linting error, such as

{[...new Array(n)].map((_, index) => <MyComponent key={index} />)}

Even this piece of code does the same job.

<tbody>
   {array.map(i => 
      <ObjectRow key={i.id} name={i.name} />
   )}
</tbody>

render() {
  const elements = ['one', 'two', 'three'];

  const items = []

  for (const [index, value] of elements.entries()) {
    items.push(<li key={index}>{value}</li>)
  }

  return (
    <div>
      {items}
    </div>
  )
}

if numrows is a array, and it's very simple.

<tbody>
   {numrows.map(item => <ObjectRow />)}
</tbody>

Array data type in React is very better, array can back new array, and support filter, reduce etc.


Inside your render or any function and before return, you can use a variable to store JSX elements. Just like this -

const tbodyContent = [];
for (let i=0; i < numrows; i++) {
    tbodyContent.push(<ObjectRow/>);
}

Use it inside your tbody like this:

<tbody>
    {
        tbodyContent
    }
</tbody>

But I'll prefer map() over this.


Below are possible solutions that you can do in React in terms of iterating array of objects or plain array

const rows = [];
const numrows = [{"id" : 01, "name" : "abc"}];
numrows.map((data, i) => {
    rows.push(<ObjectRow key={data.id} name={data.name}/>);
});

<tbody>
    { rows }
</tbody>

Or

const rows = [];
const numrows = [1,2,3,4,5];
for(let i=1, i <= numrows.length; i++){
    rows.push(<ObjectRow key={numrows[i]} />);
};

<tbody>
    { rows }
</tbody>

An even more better approach I became familiar with recent days for iterating an array of objects is .map directly in the render with return or without return:

.map with return

 const numrows = [{"id" : 01, "name" : "abc"}];
 <tbody>
     {numrows.map(data=> {
         return <ObjectRow key={data.id} name={data.name}/>
     })}
</tbody>

.map without return

 const numrows = [{"id" : 01, "name" : "abc"}];
 <tbody>
     {numrows.map(data=> (
         <ObjectRow key={data.id} name={data.name}/>
     ))}
</tbody>

I have seen one person/previous answer use .concat() in an array, but not like this...

I have used concat to add to a string and then just render the JSX content on the element via the jQuery selector:

let list = "<div><ul>";

for (let i=0; i<myArray.length; i++) {
    list = list.concat(`<li>${myArray[i].valueYouWant}</li>`);
}

list = list.concat("</ul></div>);

$("#myItem").html(list);

I use this:

gridItems = this.state.applications.map(app =>
          <ApplicationItem key={app.Id} app={app } />
);

PS: never forget the key or you will have a lot of warnings!


If you're already using lodash, the _.times function is handy.

import React, { Component } from "react";
import Select from "./Select";
import _ from "lodash";

export default class App extends Component {
  render() {
    return (
      <div className="container">
        <ol>
          {_.times(3, (i) => (
            <li key={i}>
              <Select onSelect={this.onSelect}>
                <option value="1">bacon</option>
                <option value="2">cheez</option>
              </Select>
            </li>
          ))}
        </ol>
      </div>
    );
  }
}

Simply use .map() to loop through your collection and return <ObjectRow> items with props from each iteration.

Assuming objects is an array somewhere...

<tbody>
  { objects.map((obj, index) => <ObjectRow obj={ obj } key={ index }/> ) }
</tbody>

You have to write in JSX:

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

Simply using map Array method with ES6 syntax:

<tbody>
  {items.map(item => <ObjectRow key={item.id} name={item.name} />)} 
</tbody>

Don't forget the key property.


You can create a new component like below:

Pass key and data to your ObjectRow component like this:

export const ObjectRow = ({key,data}) => {
    return (
      <div>
          ...
      </div>
    );
}

Create a new component ObjectRowList to act like a container for your data:

export const ObjectRowList = (objectRows) => {
    return (
      <tbody>
        {objectRows.map((row, index) => (
          <ObjectRow key={index} data={row} />
        ))}
      </tbody>
    );
}

Well, here you go.

{
    [1, 2, 3, 4, 5, 6].map((value, index) => {
        return <div key={index}>{value}</div>
    })
}

All you have to do is just map your array and return whatever you want to render. And please don't forget to use key in the returned element.


You'll want to add elements to an array and render the array of elements.
This can help reduce the time required to re-render the component.

Here's some rough code that might help:

MyClass extends Component {
    constructor() {
        super(props)
        this.state = { elements: [] }
    }
    render() {
        return (<tbody>{this.state.elements}<tbody>)
    }
    add() {
        /*
         * The line below is a cheap way of adding to an array in the state.
         * 1) Add <tr> to this.state.elements
         * 2) Trigger a lifecycle update.
         */
        this.setState({
            elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>])
        })
    }
}

Since you are writing Javascript syntax inside JSX code, you need to wrap your Javascript in curly braces.

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

There are many solutions posted out there in terms of iterating an array and generating JSX elements. All of them are good, but all of them used an index directly in a loop. We are recommended to use unique id from data as a key, but when we do not have a unique id from each object in the array we will use index as a key, but you are not recommended to use an index as a key directly.

One more thing why we go for .map, but why not .foEach because .map returns a new array. There are different ways of doing .map these days.

Below different versions of using .map illustrates in detail about how to use a unique key and how to use .map for looping JSX elements.

.map without return when returning single a JSX element and unique id from data as a key version:

const {objects} = this.state;

<tbody>
    {objects.map(object => <ObjectRow obj={object} key={object.id} />)}
</tbody>

.map without return when returning multiple JSX elements and unique id from data as a key version

const {objects} = this.state;

<tbody>
    {objects.map(object => (
        <div key={object.id}>
            <ObjectRow obj={object} />
        </div>
    ))}
</tbody>

.map without return when returning a single JSX element and index as a key version:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => <ObjectRow obj={object} key={`Key${index}`} />)}
</tbody>

.map without return when returning multiple JSX elements and index as a key version:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => (
        <div key={`Key${index}`}>
            <ObjectRow obj={object} />
        </div>
    ))}
</tbody>

.map with return when returning multiple JSX elements and index as a key version:

const {objects} = this.state;

<tbody>
    {objects.map((object, index) => {
        return (
            <div key={`Key${index}`}>
                <ObjectRow obj={object} />
            </div>
        )
    })}
</tbody>

.map with return when returning multiple JSX elements and unique id from data as a key version:

const {objects} = this.state;

<tbody>
    {objects.map(object => {
        return (
            <div key={object.id}>
                <ObjectRow obj={object} />
            </div>
        )
    })}
</tbody>

The other way is

render() {
  const {objects} = this.state;
  const objectItems = objects.map(object => {
       return (
           <div key={object.id}>
               <ObjectRow obj={object} />
           </div>
       )
  })
  return(
      <div>
          <tbody>
              {objectItems}
          </tbody>
      </div>
   )
}

There are multiple ways to go about doing this. JSX eventually gets compiled to JavaScript, so as long as you're writing valid JavaScript, you'll be good.

My answer aims to consolidate all the wonderful ways already presented here:

If you do not have an array of object, simply the number of rows:

within the return block, creating an Array and using Array.prototype.map:

render() {
  return (
    <tbody>
      {Array(numrows).fill(null).map((value, index) => (
        <ObjectRow key={index}>
      ))}
    </tbody>
  );
}

outside the return block, simply use a normal JavaScript for-loop:

render() {
  let rows = [];
  for (let i = 0; i < numrows; i++) {
    rows.push(<ObjectRow key={i}/>);
  } 
  return (
    <tbody>{rows}</tbody>
  );
}

immediately invoked function expression:

render() {
  return (
    <tbody>
      {() => {
        let rows = [];
        for (let i = 0; i < numrows; i++) {
          rows.push(<ObjectRow key={i}/>);
        }
        return rows;
      }}
    </tbody>
  );
}

If you have an array of objects

within the return block, .map() each object to a <ObjectRow> component:

render() {
  return (
    <tbody>
      {objectRows.map((row, index) => (
        <ObjectRow key={index} data={row} />
      ))}
    </tbody>
  );
}

outside the return block, simply use a normal JavaScript for-loop:

render() {
  let rows = [];
  for (let i = 0; i < objectRows.length; i++) {
    rows.push(<ObjectRow key={i} data={objectRows[i]} />);
  } 
  return (
    <tbody>{rows}</tbody>
  );
}

immediately invoked function expression:

render() {
  return (
    <tbody>
      {(() => {
        const rows = [];
        for (let i = 0; i < objectRows.length; i++) {
          rows.push(<ObjectRow key={i} data={objectRows[i]} />);
        }
        return rows;
      })()}
    </tbody>
  );
}

return (
    <table>
       <tbody>
          {
            numrows.map((item, index) => {
              <ObjectRow data={item} key={index}>
            })
          }
       </tbody>
    </table>
);

Use the map function. It will help you.

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

To provide a more straightforward solution in case you want to use a specific row count which is stored as Integer-value.

With the help of typedArrays we could achieve the desired solution in the following manner.

// Let's create a typedArray with length of `numrows`-value
const typedArray = new Int8Array(numrows); // typedArray.length is now 2
const rows = []; // Prepare rows-array
for (let arrKey in typedArray) { // Iterate keys of typedArray
  rows.push(<ObjectRow key={arrKey} />); // Push to an rows-array
}
// Return rows
return <tbody>{rows}</tbody>;

Use {} around JavaScript code within a JSX block to get it to properly perform whatever JavaScript action you are trying to do.

<tr>
  <td>
    {data.map((item, index) => {
      {item}
    })}
  </td>
</tr>

This is kind of vague, but you can swap out data for any array. This will give you a table row and table item for each item. If you have more than just one thing in each node of the array, you will want to target that specifically by doing something like this:

<td>{item.someProperty}</td>

In which case, you will want to surround it with a different td and arrange the previous example differently.


Maybe the standard of today maximum developer, use a structure like this:

 let data = [
  {
    id: 1,
    name: "name1"
  },
  {
    id: 2,
    name: "name2"
  },
  {
    id: 3,
    name: "name3"
  },
  {
    id: 100,
    name: "another name"
  }
];

export const Row = data => {
  return (
    <tr key={data.id}>
      <td>{data.id}</td>
      <td>{data.name}</td>
    </tr>
  );
};

function App() {
  return (
    <table>
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>{data.map(item => Row(item))}</tbody>
    </table>
  );
}

In the JSX, write your JavaScript action inside HTML or any code here, {data.map(item => Row(item))}, use single curly braces and inside a map function. Get to know more about map.

And also see the following output here.


Array.from is the best way. If you want to create an array of JSX with some length.

function App() {
  return (
    <tbody>
      {Array.from({ length: 10 }, (_, key) => (
        <ObjectRow {...{ key }} />
      ))}
    </tbody>
  );
}

The above example is for when you do not have an array, so if you have an array you should map it in JSX like this:

function App() {
  return (
    <tbody>
      {list.map((item, key) => (
        <ObjectRow {...{ key }} />
      ))}
    </tbody>
  );
}

Your JSX code will compile into pure JavaScript code, any tags will be replaced by ReactElement objects. In JavaScript, you cannot call a function multiple times to collect their returned variables.

It is illegal, the only way is to use an array to store the function returned variables.

Or you can use Array.prototype.map which is available since JavaScript ES5 to handle this situation.

Maybe we can write other compiler to recreate a new JSX syntax to implement a repeat function just like Angular's ng-repeat.


A loop inside JSX is very simple. Try this:

return this.state.data.map((item,index) => <ComponentName key={index} data={item}/>);

If numrows is an array, as the other answers, the best way is the map method. If it's not and you only access it from JSX, you can also use this ES6 method:

<tbody>
    {
      [...Array(numrows).fill(0)].map((value,index)=><ObjectRow key={index} />)
    }
</tbody>

There are several answers pointing to using the map statement. Here is a complete example using an iterator within the FeatureList component to list Feature components based on a JSON data structure called features.

const FeatureList = ({ features, onClickFeature, onClickLikes }) => (
  <div className="feature-list">
    {features.map(feature =>
      <Feature
        key={feature.id}
        {...feature}
        onClickFeature={() => onClickFeature(feature.id)}
        onClickLikes={() => onClickLikes(feature.id)}
      />
    )}
  </div>
); 

You can view the complete FeatureList code on GitHub. The features fixture is listed here.


The problem is you don't return any JSX element. There are another solutions for such cases, but I will provide the simplest one: "use the map function"!

<tbody>
  { numrows.map(item => <ObjectRow key={item.uniqueField} />) }
</tbody>

It's so simple and beautiful, isn't it?


ES2015 Array.from with the map function + key

If you have nothing to .map() you can use Array.from() with the map function to repeat elements:

<tbody>
  {Array.from({ length: 5 }, (value, key) => <ObjectRow key={key} />)}
</tbody>

It's funny how people give "creative" answers using a newer syntax or uncommon ways to create an array. In my experience working with JSX, I have seen these tricks only used by inexperienced React programmers.

The simpler the solution - the better it is for future maintainers. And since React is a web framework, usually this type of (table) data comes from the API. Therefore, the simplest and most practical way would be:

const tableRows = [
   {id: 1, title: 'row1'}, 
   {id: 2, title: 'row2'}, 
   {id: 3, title: 'row3'}
]; // Data from the API (domain-driven names would be better of course)
...

return (
   tableRows.map(row => <ObjectRow key={row.id} {...row} />)
);




You can also extract outside the return block:

render: function() {
    var rows = [];
    for (var i = 0; i < numrows; i++) {
        rows.push(<ObjectRow key={i}/>);
    } 

    return (<tbody>{rows}</tbody>);
}

I am not sure if this will work for your situation, but often [map][1] 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 the map function:

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

objects.map is the best way to do a loop, and objects.filter is the best way to filter the required data. The filtered data will form a new array, and objects.some is the best way to check whether the array satisfies the given condition (it returns Boolean).


There are multiple ways to loop inside JSX

  1. Using a for loop

    function TableBodyForLoop(props) {
      const rows = []; // Create an array to store list of tr
    
      for (let i = 0; i < props.people.length; i++) {
        const person = props.people[i];
        // Push the tr to array, the key is important
        rows.push(
          <tr key={person.id}>
            <td>{person.id}</td>
            <td>{person.name}</td>
          </tr>
        );
      }
    
      // Return the rows inside the tbody
      return <tbody>{rows}</tbody>;
    }
    
  2. Using the ES6 array map method

    function TableBody(props) {
      return (
        <tbody>
          {props.people.map(person => (
            <tr key={person.id}>
              <td>{person.id}</td>
              <td>{person.name}</td>
            </tr>
          ))}
        </tbody>
      );
    }
    
    

Full example: https://codesandbox.io/s/cocky-meitner-yztif

The following React Docs will be helpful


...Or you can also prepare an array of objects and map it to a function to have the desired output. I prefer this, because it helps me to maintain the good practice of coding with no logic inside the return of render.

render() {
const mapItem = [];
for(let i =0;i<item.length;i++) 
  mapItem.push(i);
const singleItem => (item, index) {
 // item the single item in the array 
 // the index of the item in the array
 // can implement any logic here
 return (
  <ObjectRow/>
)

}
  return(
   <tbody>{mapItem.map(singleItem)}</tbody>
  )
}

You might want to checkout React Templates, which does let you use JSX-style templates in React, with a few directives (such as rt-repeat).

Your example, if you used react-templates, would be:

<tbody>
     <ObjectRow rt-repeat="obj in objects"/>
</tbody>

Using map in React are best practices for iterating over an array.

To prevent some errors with ES6, the syntax map is used like this in React:

<tbody>
    {items.map((item, index) => <ObjectRow key={index} name={item.name} />)}
</tbody>

Here you call a Component, <ObjectRow/>, so you don't need to put parenthesis after the arrow.

But you can be make this too:

{items.map((item, index) => (
    <ObjectRow key={index} name={item.name} />
))}

Or:

{items.map((item, index) => {
    // Here you can log 'item'
    return (
        <ObjectRow key={index} name={item.name} />
    )
})}

I say that because if you put a bracket "{}" after the arrow React will not throw an error and will display a whitelist.


Here is a sample from React doc:JavaScript Expressions as Children

function Item(props) {
  return <li>{props.message}</li>;
}

function TodoList() {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((message) => <Item key={message} message={message} />)}
    </ul>
  );
}

as your case, I suggest writing like this:

function render() {
  return (
    <tbody>
      {numrows.map((roe, index) => <ObjectRow key={index} />)}
    </tbody>
  );
}

Please notice the Key is very important, because React use Key to differ data in array.


@jacefarm If I understand right you can use this code:

<tbody>
    { new Array(numrows).fill(<ObjectRow/>) } 
</tbody>

Either you can use this code:

<tbody>
   { new Array(numrows).fill('').map((item, ind) => <ObjectRow key={ind}/>) } 
</tbody>

And this:

<tbody>
    new Array(numrows).fill(ObjectRow).map((Item, ind) => <Item key={ind}/>)
</tbody>

I use it like

<tbody>
  { numrows ? (
     numrows.map(obj => { return <ObjectRow /> }) 
    ) : null
  }
</tbody>

If you don't already have an array to map() like @FakeRainBrigand's answer, and want to inline this so the source layout corresponds to the output closer than @SophieAlpert's answer:

With ES2015 (ES6) syntax (spread and arrow functions)

http://plnkr.co/edit/mfqFWODVy8dKQQOkIEGV?p=preview

<tbody>
  {[...Array(10)].map((x, i) =>
    <ObjectRow key={i} />
  )}
</tbody>

Re: transpiling with Babel, its caveats page says that Array.from is required for spread, but at present (v5.8.23) that does not seem to be the case when spreading an actual Array. I have a documentation issue open to clarify that. But use at your own risk or polyfill.

Vanilla ES5

Array.apply

<tbody>
  {Array.apply(0, Array(10)).map(function (x, i) {
    return <ObjectRow key={i} />;
  })}
</tbody>

Inline IIFE

http://plnkr.co/edit/4kQjdTzd4w69g8Suu2hT?p=preview

<tbody>
  {(function (rows, i, len) {
    while (++i <= len) {
      rows.push(<ObjectRow key={i} />)
    }
    return rows;
  })([], 0, 10)}
</tbody>

Combination of techniques from other answers

Keep the source layout corresponding to the output, but make the inlined part more compact:

render: function () {
  var rows = [], i = 0, len = 10;
  while (++i <= len) rows.push(i);

  return (
    <tbody>
      {rows.map(function (i) {
        return <ObjectRow key={i} index={i} />;
      })}
    </tbody>
  );
}

With ES2015 syntax & Array methods

With Array.prototype.fill you could do this as an alternative to using spread as illustrated above:

<tbody>
  {Array(10).fill(1).map((el, i) =>
    <ObjectRow key={i} />
  )}
</tbody>

(I think you could actually omit any argument to fill(), but I'm not 100% on that.) Thanks to @FakeRainBrigand for correcting my mistake in an earlier version of the fill() solution (see revisions).

key

In all cases the key attr alleviates a warning with the development build, but isn't accessible in the child. You can pass an extra attr if you want the index available in the child. See Lists and Keys for discussion.


Unless you declare a function and enclose it with parameters, it is not possible. In a JSXExpression you can only write expressions and cannot write statements like a for(), declare variables or classes, or a if() statement.

That's why function CallExpressions are so in the mood today. My advice: get used to them. This is what I would do:

const names = ['foo', 'bar', 'seba']
const people = <ul>{names.map(name => <li>{name}</li>)}</ul>

Filtering:

const names = ['foo', undefined, 'seba']
const people = <ul>{names.filter(person => !!person).map(name => <li>{name}</li>)}</ul>

if():

var names = getNames()
const people = {names && names.length &&
   <ul>{names.map(name => <li>{name}</li>)}</ul> }

if - else:

var names = getNames()
const people = {names && names.length ?
  <ul>{names.map(name => <li>{name}</li>)}</ul> : <p>no results</p> }

Here's a simple solution to it.

var Object_rows = [];
for (var i = 0; i < numrows; i++) {
  Object_rows.push(<ObjectRow />);
}
<tbody>{Object_rows}</tbody>;

No mapping and complex code required. You just need to push the rows to the array and return the values to render it.


I've found one more solution to follow the map render:

 <tbody>{this.getcontent()}</tbody>

And a separate function:

getcontent() {
    const bodyarea = this.state.movies.map(movies => (
        <tr key={movies._id}>
            <td>{movies.title}</td>
            <td>{movies.genre.name}</td>
            <td>{movies.numberInStock}</td>
            <td>{movies.publishDate}</td>
            <td>
                <button
                    onClick={this.deletMovie.bind(this, movies._id)}
                    className="btn btn-danger"
                >
                    Delete
                </button>
            </td>
        </tr>
    ));
    return bodyarea;
}

This example solves many problems easily.


function PriceList({ self }) {
    let p = 10000;
    let rows = [];
    for(let i=0; i<p; i=i+50) {
        let r = i + 50;
        rows.push(<Dropdown.Item key={i} onClick={() => self.setState({ searchPrice: `${i}-${r}` })}>{i}-{r} &#8378;</Dropdown.Item>);
    }
    return rows;
}

<PriceList self={this} />

If you need JavaScript code inside your JSX, you add { } and then write your JavaScript code inside these brackets. It is just that simple.

And the same way you can loop inside JSX/react.

Say:

<tbody>
    {`your piece of code in JavaScript` }
</tbody>

Example:

<tbody>
    { items.map((item, index) => {
        console.log(item)}) ; // Print item
        return <span>{index}</span>;
    } // Looping using map()
</tbody>

You can only write a JavaScript expression in a JSX element, so a for loop cannot work. You can convert the element into an array first and use the map function to render it:

<tbody>
    {[...new Array(numrows)].map((e) => (
         <ObjectRow/>
    ))}
</tbody>

You can try the new for of loop:

const apple = {
    color: 'red',
    size: 'medium',
    weight: 12,
    sugar: 10
}
for (const prop of apple.entries()){
    console.log(prop);
}

Here's a few examples:


let us say we have an array of items in your state:

[{name: "item1", id: 1}, {name: "item2", id: 2}, {name: "item3", id: 3}]

<tbody>
    {this.state.items.map((item) => {
        <ObjectRow key={item.id} name={item.name} />
    })} 
</tbody>

You can use an IIFE if you really want to literally use a for loop inside JSX.

<tbody>
  {
    (function () {
      const view = [];
      for (let i = 0; i < numrows; i++) {
        view.push(<ObjectRow key={i}/>);
      }
      return view;
    }())
  }
</tbody>

const numrows = [1, 2, 3, 4, 5];

cosnt renderRows = () => {
    return numros.map((itm,index) => <td key={index}>{itm}</td>)
}

return <table>
    ............
    <tr>
        {renderRows()}
    </tr>
</table>

<tbody>
   numrows.map((row,index) => (
      return <ObjectRow key={index}/>
   )
</tbody>

Having the JSX content in the map can be clunky syntax. Instead you can do this:

const ObjectRow = ({ ... }) => <tr key={}>...</tr>

const TableBody = ({ objects }) => {
  return <tbody>{objects.map(ObjectRow)}</tbody>;
}

This is shorthand for

{ objects.map(object => ObjectRow(object))

If ObjectRow is set up to take the same keys that are in the object, this will work great.

Note - You may need to set the key prop when the ObjectRow is rendered. It can't be passed in through the function call.


More notes - I've run into a few places where this technique is a bad idea. For example, it doesn't go through the normal create component path and won't default prop values for example, so do beware. Still, it's handy to know about and is useful sometimes.


You can also use a self-invoking function:

return <tbody>
           {(() => {
              let row = []
              for (var i = 0; i < numrows; i++) {
                  row.push(<ObjectRow key={i} />)
              }
              return row

           })()}
        </tbody>

If you opt to convert this inside return( ) of render method, easiest option would be using map( ) method. Map your array into JSX syntax using map() function, as shown below (ES6 syntax is used).


Inside parent component:

<tbody>
   { objectArray.map(object => <ObjectRow key={object.id} object={object.value}>) }
</tbody>

Please note the key attribute added to your child component. If you didn't provide a key attribute, you can see the following warning on your console.

Warning: Each child in an array or iterator should have a unique "key" prop.

Note: One common mistake people do is using index as key when iterating, using index of the element as a key is an anti-pattern and you can read more about it here. In short, if it's NOT a static list never use index as key.


Now at the ObjectRow component, you can access the object from its properties.

Inside ObjectRow component

const { object } = this.props

or

const object = this.props.object

This should fetch you the object you passed from parent component to the variable object in ObjectRow component. Now you can spit out the values in that object according to your purpose.


References :

map() method in Javascript

ECMA Script 6 or ES6


If you are used to Angular and want a more React-like approach:

Try using this simple component with auto hashing and optional trackBy similar to Angular's.

Usage:

<For items={items}>
    {item => <div>item</div>}
</For>

Custom key/trackBy:

<For items={items} trackBy={'name'}>
    {item => <div>item</div>}
</For>

Definition:

export default class For<T> extends Component<{ items: T[], trackBy?: keyof T, children: (item: T) => React.ReactElement }, {}> {
    render() {
        return (
            <Fragment>
                {this.props.items.map((item: any, index) => <Fragment key={this.props.trackBy ?? item.id ?? index}>{this.props.children(item)}</Fragment>)}
            </Fragment>
        );
    }
}

React Dev Tools:

Enter image description here


React elements are simple JS, so you can follow the rule of javascript. So you can use a for loop in javascript like this:-

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

But the valid and best way is to use the .map function. Shown below:-

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

Here, one thing is necessary: to define the key. Otherwise it will throw a warning like this:-

warning.js:36 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of ComponentName. See "link" for more information.


For printing an array value if you don't have the key value par, then use the below code -

<div>
    {my_arr.map(item => <div>{item} </div> )}                    
</div>

you can of course solve with a .map as suggested by the other answer. If you already use babel, you could think about using jsx-control-statements They require a little of setting, but I think it's worth in terms of readability (especially for non-react developer). If you use a linter, there's also eslint-plugin-jsx-control-statements


Using Array map function is a very common way to loop through an Array of elements and create components according to them in React, this is a great way to do a loop which is a pretty efficient and tidy way to do your loops in JSX, It's not the only way to do it, but the preferred way.

Also, don't forget having a unique Key for each iteration as required. Map function creates a unique index from 0 but it's not recommended using the produced index but if your value is unique or if there is a unique key, you can use them:

<tbody>
  {numrows.map(x=> <ObjectRow key={x.id} />)}
</tbody>

Also, few lines from MDN if you not familiar with map function on Array:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

If a thisArg parameter is provided to the map, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value. This value ultimately observable by the callback is determined according to the usual rules for determining the this seen by a function.

map does not mutate the array on which it is called (although callback, if invoked, may do so).


An ES2015 / Babel possibility is using a generator function to create an array of JSX:

function* jsxLoop(times, callback)
{
    for(var i = 0; i < times; ++i)
        yield callback(i);
}

...

<tbody>
    {[...jsxLoop(numrows, i =>
        <ObjectRow key={i}/>
    )]}
</tbody>

This can be done in multple ways.

  1. As suggested above, before return store all elements in the array

  2. Loop inside return

    Method 1

     let container =[];
        let arr = [1,2,3] //can be anything array, object 
    
        arr.forEach((val,index)=>{
          container.push(<div key={index}>
                         val
                         </div>)
            /** 
            * 1. All loop generated elements require a key 
            * 2. only one parent element can be placed in Array
            * e.g. container.push(<div key={index}>
                                        val
                                  </div>
                                  <div>
                                  this will throw error
                                  </div>  
                                )
            **/   
        });
        return (
          <div>
             <div>any things goes here</div>
             <div>{container}</div>
          </div>
        )
    

    Method 2

       return(
         <div>
         <div>any things goes here</div>
         <div>
            {(()=>{
              let container =[];
              let arr = [1,2,3] //can be anything array, object 
              arr.forEach((val,index)=>{
                container.push(<div key={index}>
                               val
                               </div>)
                             });
                        return container;     
            })()}
    
         </div>
      </div>
    )
    

To loop for a number of times and return, you can achieve it with the help of from and map:

<tbody>
  {
    Array.from(Array(i)).map(() => <ObjectRow />)
  }
</tbody>

where i = number of times


If you want to assign unique key IDs into the rendered components, you can use React.Children.toArray as proposed in the React documentation

React.Children.toArray

Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.

Note:

React.Children.toArray() changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.

<tbody>
  {
    React.Children.toArray(
      Array.from(Array(i)).map(() => <ObjectRow />)
    )
  }
</tbody>

Simple way

You can put numrows in state and use map() instead of a for loop:

{this.state.numrows.map((numrows , index) => {
      return (
        <ObjectRow
          key={index}
        />

You can do something like:

let foo = [1,undefined,3]
{ foo.map(e => !!e ? <Object /> : null )}

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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to jsx

TypeScript and React - children type? How to use componentWillMount() in React Hooks? expected assignment or function call: no-unused-expressions ReactJS You should not use <Link> outside a <Router> ReactJS - .JS vs .JSX React: Expected an assignment or function call and instead saw an expression React-Native Button style not work ReactJs: What should the PropTypes be for this.props.children? ReactJS map through Object Console logging for react?