Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

React: loop inside JSX code

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

class HelloWorld extends React.Component {
	render() {
		return 

Hello World

; } }

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

class HelloWorldMultiple extends React.Component {
  render() {
    return 

for (let i=0; i }

; } }

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

How to correctly loop inside JSX

class HelloWorldMultiple extends React.Component {
  render() {
    let rows = [];
    for (let i=0; i )
    }
    return 

{rows}

; } }

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 a IIFE

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

class HelloWorldMultiple extends React.Component {
  render() {
    return 

{ function() { let rows = []; for (let i=0; i ); } return rows; }() }

} }

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

class HelloWorldMultiple extends React.Component {
	render() {
    let rows = [];
    for (let i=0; i 
             { rows.map((object, i) => ) }
           
	}
}

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.

The post React: loop inside JSX code appeared first on Just Think.



This post first appeared on Just Think, please read the originial post: here

Share the post

React: loop inside JSX code

×

Subscribe to Just Think

Get updates delivered right to your inbox!

Thank you for your subscription

×