How to create for loop inside React JSX?

Total
0
Shares

Yes you an create a for loop inside react JSX with the help of function callback approach. In fact, you can run any code within JSX using this approach. But it is advised not to use it because every time JSX renders, a new function will be instantiated. This should be avoided for performance optimization.

For educational purpose you should know different ways in which a work could be done. So, we are going to see this approach.

Consider this example –

export default function App(){
  return(
    <div>
      for(var i=0; i<5; i++){
        <p>{i}</p>
      }
    </div>
  )
}

This won’t run because you can’t use JS code within JSX without enclosing them in {}. The curly braces are used to run an expression. The expression could be one line calculation, a method call, or a ternary condition. But you can’t have variable declaration or loops or any other complex stuff in them.

So, this code is also wrong –

export default function App(){
  return(
    <div>
      {
        for(var i=0; i<5; i++){
          <p>{i}</p>
        }
      }
    </div>
  )
}

Then what’s the way to run a for loop inside JSX? Well, we have to use callback approach. Check this code –

export default function App() {
  const runCallback = (cb) => {
    return cb();
  };

  return (
    <div>
      {
        runCallback(() => {
          const row = [];
          for (var i = 0; i < 5; i++) {
            row.push(<p key={i}>{i}</p>);
          }
          return row;
        })
      }
    </div>
  );
}

This code will work because ideally we are just calling a function runCallback() within {}. All the code including constant row declaration and for loop will run as a callback function in runCallback(). This approach is not recommended because whenever the App component render, a new anonymous callback function will create. But this works.

Note: You should always use key in elements returned from loops. Learn more from here.

The recommended approach is to use map() function or take out the callback code in separate function and call that function in JSX.

Code example using map() –

export default function App(){
  return(
    <div>
      {
        [0,1,2,3,4].map((i) => (
          <p key={i}>{i}</p>
        ))
      }
    </div>
  )
}

Code example for separate function –

export default function App() {
  const printNumbers0To5 = () => {
    const row = [];
    for (var i = 0; i < 5; i++) {
      row.push(<p key={i}>{i}</p>);
    }
    return row;
  };

  return (
    <div>
      {
        printNumbers0To5()
      }
    </div>
  );
}

    Tweet this to help others

Live Demo

Open Live Demo