Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over a number in React inside JSX

I need to be able to loop over a number and return some jsx. For example

<ul>  {for(i =0; i < 10; i++){    return <li>{i}</li>  }} </ul> 

This is not exactly what I want to do, but if I can solve this then I should be able to complete what I need to do. This however returns expression expected on the for. I have done some research and people say you can't use for loops inside of jsx because they do not return anything.

How do I go about looping over a number to return some amount of jsx?

like image 660
Taylor Austin Avatar asked Nov 14 '17 13:11

Taylor Austin


People also ask

Can we use loop inside JSX?

Using the 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 is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.

How do you loop through an object in React JSX?

Use the Object. keys() method to get an array of the object's keys. Use the map() method to iterate over the array of keys.


2 Answers

You could use Array.from() instead.

let App = () => {    return <ul>{Array.from(Array(10), (e, i) => {      return <li key={i}>{i}</li>    })}</ul>  }    ReactDOM.render(    <App />,    document.getElementById('app')  );
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>  <div id="app"></div>

You can also use ES6 spread syntax with map() method.

let App = () => {    return <ul>{[...Array(10)].map((e, i) => {      return <li key={i}>{i}</li>    })}</ul>  }    ReactDOM.render(    <App />,    document.getElementById('app')  );
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>  <div id="app"></div>
like image 100
Nenad Vracar Avatar answered Oct 11 '22 17:10

Nenad Vracar


You can do it like this :

createElements(n){     var elements = [];     for(i =0; i < n; i++){         elements.push(<li>{i}</li>);     }     return elements; }  <ul>     {this.createElements(20)} </ul> 
like image 45
Vivek Doshi Avatar answered Oct 11 '22 16:10

Vivek Doshi