How to render elements using a while loop.
while(condition){
return (<div> {something} <div>);
}
How to render elements using a while loop.
while(condition){
return (<div> {something} <div>);
}
Normally in this situation you build an array and return it:
const result = [];
while (condition) {
result.push(<div key={appropriateKeyForThisSomething}>{something}</div>);
}
return result;
Note that it's important to include the key
property on the top-level element of each entry in the array. React needs it to avoid unnecessary re-rendering and DOM manipulations. More here. Note that if the contents of the array can change over time, just using an index is usually not best practice.
It's recommended by react docs to use Array.prototype.map
for converting arrays to JSX.
If you specifically only want to use the while loop then T.J has the right solution for you.
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>{number}</li>
);
Link to react doc for lists