React: loop inside JSX code

Add React JS component multiple times with jsx loop

Add React JS component multiple times with jsx loop

If you are using React JS and want to add a component multiple times, maybe inserting it into some JSX code, you could think of using a for loop inside the return statement of your JSX.

But this approach doesn’t work in JSX, as you should compose the returned value from the render function of values, while a for loop is an imperative way of doing thing and doesn’t return anything.

Suppose you want to print four times the Hello World string.
We build a basic component Hello World, the following one

Then, we try to add it multiple times to some JSX code.

The wrong approach

What you probably have done so far is trying something like

This doesn’t work, so let’s see the correct approach

How to correctly loop inside JSX

Here we see how a component named HelloWorldMultiple can add another component Hello World multiple times:

  1. create an array of rows containing the basic component
  2. add the just created array to your “template” using curly braces

How to add a component multiple times with an IIFE

You can also use an IIFE (Immediately-invoked function expression), which returns a result and so its ok

How to loop inside JSX with map

If you already have an array of objects and want to add them into your template,  you can use map this way

The complete example

What follows is the complete example of our code to print Hello World four times inside an h1 HTML tag. This is only to show how the code should be and uses Babel standalone, real code should be precompiled using Babel with a module bundler like Browserify or Webpack

Babel repl

To better understand why you need to use the for outside the return statement, you can use Babel REPL, which translates JSX code into vanilla Javascript on the fly.