close

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

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to do a nested if else statement in ReactJS JSX? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

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

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

    to do a nested if else statement in ReactJS JSX Instead of nesting ternary operators as it is often suggested or creating a separate function that will not be reused anywhere else, you can simply call an inline expression:

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

    to do a nested if else statement in ReactJS JSX Instead of nesting ternary operators as it is often suggested or creating a separate function that will not be reused anywhere else, you can simply call an inline expression:

Method 1

You need to wrap your title and body in a container. That could be a div. If you use a list 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 key='0'>some title</div>
        : null
      ),
      <div key='1'>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 key='0'>some title</div>),
    <div key='1'>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).

Method 2

Instead of nesting ternary operators as it is often suggested or creating a separate function that will not be reused anywhere else, you can simply call an inline expression:

<div className="some-container">
{
   (() => {
       if (conditionOne)
          return <span>One</span>
       if (conditionTwo)
          return <span>Two</span>
       else (conditionOne)
          return <span>Three</span>
   })()
}
</div>

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment