using array Map In ReactJS

By using Map you can do almost anything that a for loop does. Also, Map returns an array so there won’t be any Compilation Error. Don’t forget to add a key prop while returning every component.

Syntax: 

{ arr.map((parameter) => (//logic) )}

Javascript




// Filename - App.js
  
import React from "react";
  
function App() {
    const items = [1, 2, 3, 4, 5];
    return (
        <div>
            {items.map((item, index) => (
                <div key={index}> 
                    Hello World {item} 
                </div>
            ))}
        </div>
    );
}
  
export default App;


Step to run the application: Open the terminal and type the following command.

npm start

Output: Now open your browser and go to http://localhost:3000/ 

Alternatives of for loops and if-else blocks in ReactJS

Implementing loops in React generally gives the error stating Unexpected token and the same error shows up if you use if conditions as well. There we have alternatives to be used in JSX in react.

Syntax for Loop in React:

function App() {
  return (
    <div>
        {for(let i =0 ; i< 5 ; i++)
             </Component>}
    </div>
}

Explanation: Browser doesn’t understand react.js so webpack such as Babel converts React.js into JavaScript at compilation. Everything in React.js boils down to plain JavaScript. So if you write something in react.js that isn’t a valid JavaScript then you will get a Compilation Error. The problem in the above code is that the return statement always expects a value but a for loop if the block does not return any value. So the alternatives to using these should return something.

These are the alternatives for loops and if-else in React JSX:

Table of Content

  • using array Map
  • for loop but outside of return statement
  • Alternative for If-else – Ternary Operator

Similar Reads

Steps to Create React Application:

Step 1: Creating React Application...

Method 1: using array Map

By using Map you can do almost anything that a for loop does. Also, Map returns an array so there won’t be any Compilation Error. Don’t forget to add a key prop while returning every component....

Method 2: for loop but outside of return statement

...

Method 3: Alternative for If-else – Ternary Operator

Here we loop through the array outside of the return statement and store the array of components and then we render the array inside of the return statement....