MuhammadOsamaQureshi
MuhammadOsamaQureshi

Reputation: 73

how do I run the this condition properly in Reactjs?

** ReactJs **

    let resultDisplay=""
    if(Bmi>=18 || Bmi<=25 )
     {resultDisplay= <p>Perfect</p> 
    }

Problem is right there but I can't figure it out since I new in React

    else if(Bmi<18)
      resultDisplay=<p>to Thin</p>

`` For me looks fine any guidence and help would be great ```

    else if(Bmi>25)
      resultDisplay=<p>Overweight</p>
      setresult(resultDisplay)
    
}

Right now its only working on one condition and doesn't rendering the other conditions results

Upvotes: 1

Views: 102

Answers (3)

Veterini
Veterini

Reputation: 150

It depends how you construct your component but it would be way simplier to use ternary in your render.

Assuming it's a single value, in your states, (most common issue), or from a function, in the return of your render you can do something like

return(
<p>
{
Bmi>=18 || Bmi<=25 //if
 ? 'Perfect' //then
 : Bmi < 18 //else if else
  ? 'to Thin' //then
  :Bmi > 25 //else if else
   ? 'too heavy' //then
   : '' //it's your last else if so else is empty
: '' //last else of first if
}
</p>
)

Upvotes: 0

Ishan Sourav
Ishan Sourav

Reputation: 11

A concise way to do...

import React from "react";

function App() {
    let Bmi = 23; // some value you assigned

    let resultDisplay = ""; //to display BMI result

    if (Bmi < 18)
        resultDisplay = "Too thin"; //Less than 18 means too thin
    else if (Bmi <= 25)
        resultDisplay = "Perfect"; //otherwise >= 18 && <= 25
    else
        resultDisplay = "Overweight"; //otherwise > 25

    return (
        <div>
            <p>{resultDisplay}</p>
            {/*Wrapping by curly braces to use the javascript variable inside the JSX*/}
        </div>
    );
}

Upvotes: 1

Laurenz1606
Laurenz1606

Reputation: 98

the var resultDisplay is a string, so its not a jsx element, save your result to a string and include it in your jsx: your code

let resultDisplay=""
    if(Bmi>=18 || Bmi<=25 )
     {resultDisplay= '<p>Perfect</p>'
    }

where you display it:

<yourcomponent>{resultDisplay}<yourcomponent>

Upvotes: 1

Related Questions