-1

How to render elements using a while loop.

while(condition){
   return (<div> {something} <div>);
}
aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
  • 4
    Can you provide some context? Why is that you wanna do something like this? what is your intention. you can control what to be rendered via props or state. Im not sure if I got it right but you can receive that condition as a prop and render it based on the value using an if statement. – c0m1t Jan 11 '21 at 14:44
  • Good find @Emile! – T.J. Crowder Jan 11 '21 at 15:09

2 Answers2

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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

Sudhanshu Kumar
  • 1,926
  • 1
  • 9
  • 21