Zena Mesfin
Zena Mesfin

Reputation: 421

What is the best way to write a simple condition in JSX?

in my jsx

<div>{person.age}</div>

I want to display below only if the person is age 50 or above

<div className="red-text">{person.age}</div>

to do this I put a var let olderPerson = person.age > 50; and then did this

{
    olderPerson ? (
        <div className="red-text">{person.age }</div>
    ) : (<div >{person.age }</div>)
}

LMK if this correct way to do this

Upvotes: 0

Views: 42

Answers (2)

Mikhail Katrin
Mikhail Katrin

Reputation: 2384

For example:

https://jsfiddle.net/enf2q4eg/

Age passed via props in Example component.

Upvotes: 0

Joey van Breukelen
Joey van Breukelen

Reputation: 245

yea correct.

        {
        olderPerson ?
            <div className="red-text">{person.age }</div> :
            <div >{person.age }</div>
        }

in this case you could also make the classname conditional.

        {
        <div className={olderPerson && "red-text"}>
            {person.age }
        </div>
        }

Upvotes: 1

Related Questions