Sunday, November 17, 2024
Google search engine
HomeLanguagesAlternatives of for loops and if-else blocks in ReactJS

Alternatives of for loops and if-else blocks in ReactJS

If you have ever tried to use for loop in React then you must be familiar with the error stating Unexpected token and the same error shows up if you use if conditions as well.

Pseudo Code:

import React from 'react'
import ReactDOM from 'react-dom'
import Component from "./Component"

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

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

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 which isn’t a valid JavaScript then you will get Compilation Error. The problem in the above code is that the return statement always expects a value but a for loop and if block does not return any value. So the alternatives of using these should return something.

Step 1: Creating React Application

npx create-react-app loops

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

cd loops

Project Structure: It will look like the following.

1. For Loop Alternatives: 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) )}

App.js




import React from 'react'
import ReactDOM from 'react-dom'
  
  
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/ 

for loop but outside of return: 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 }

App.js




import React from 'react'
import ReactDOM from 'react-dom'
  
  
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/ 

2. If-else block Alternative: Ternary Operator 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 }

App.js

App.js




import React from 'react'
import ReactDOM from 'react-dom'
  
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/ 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments