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

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)