Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a nested if else statement in ReactJS JSX?

I wanted to know if its possible to do nested if else if in ReactJS JSX?

I have tried various different ways and I am unable to get it to work.

I am looking for

if (x) {   loading screen } else {   if (y) {     possible title if we need it   }   main  } 

I have tried this but I can not get it to render. I have tried various ways. It always breaks once I add the nested if.

{   this.state.loadingPage ? (     <div>loading page</div>   ) : (     <div>       this.otherCondition && <div>title</div>       <div>body</div>     </div>   ); } 

Update

I ended up choosing the solution to move this to renderContent and call the function. Both of the answers did work though. I think I may use the inline solution if it is for a simple render and renderContent for more complicated cases.

Thank you

like image 720
ALM Avatar asked May 19 '16 00:05

ALM


People also ask

Can I write if-else condition in JSX?

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

Is JSX can be used inside if and for loop?

You can basically use the same structure when working with JSX: var rows = []; for (var i = 0; i < numrows; i++) { // note: we are adding a key prop here to allow react to uniquely identify each // element in this array.

What does {} mean in JSX?

With JSX you can write expressions inside curly braces { } . The expression can be a React variable, or property, or any other valid JavaScript expression.


1 Answers

You need to wrap your title and body in a container. That could be a div. If you use a fragment instead, you'll have one less element in the dom.

{ this.state.loadingPage   ? <span className="sr-only">Loading... Registered Devices</span>   : <>       {this.state.someBoolean         ? <div>some title</div>         : null       }       <div>body</div>     </> } 

I would advise against nesting ternary statements because it's hard to read. Sometimes it's more elegant to "return early" than to use a ternary. Also, you can use isBool && component if you only want the true part of the ternary.

renderContent() {   if (this.state.loadingPage) {     return <span className="sr-only">Loading... Registered Devices</span>;   }    return (     <>       {this.state.someBoolean && <div>some title</div>}       <div>body</div>     </>   ); }  render() {   return <div className="outer-wrapper">{ this.renderContent() }</div>; } 

Caveat to the syntax someBoolean && "stuff": if by mistake, someBoolean is set to 0 or NaN, that Number will be rendered to the DOM. So if the "boolean" might be a falsy Number, it's safer to use (someBoolean ? "stuff" : null).

like image 76
Neal Ehardt Avatar answered Sep 25 '22 06:09

Neal Ehardt