Open In App

Alternatives of for loops and if-else blocks in ReactJS

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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:

Steps to Create React Application:

Step 1: Creating React Application

npx create-react-app loops

Step 2: After creating your project directory i.e.loops, move to it using the following command:

cd loops

Project Structure:

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.

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/ 

Method 2: for loop but outside of return statement

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.      

Syntax:

for(initialization; condition; updation) {  //logic }

Example: This example shows basic implementation of for loop outside the return statemment.

Javascript




// Filename - App.js
  
import React from "react";
  
function App() {
    const items = [1, 2, 3, 4, 5];
    let components = [];
    for (let i = 0; i < items.length; i++) {
        components.push(<div>Hello Word {items[i]}</div>);
    }
    return <div>{components}</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/ 

Method 3: Alternative for If-else – Ternary Operator

It does the same thing that an if-else block does. If you just want an if condition check then you can write null in the else part.

Syntax:

{ (condition) ? true : false }

Example: This example shows the basic implementation of ternary operator.

Javascript




// Filename - App.js
  
import React from "react";
  
function App() {
    const x = 12;
    return (
        <div>
            {x % 2 === 0 ? (
                <h1>x is Even</h1>
            ) : (
                <h1> x is Odd</h1>
            )}
        </div>
    );
}


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/ 



Last Updated : 11 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads