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?
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With