Home  >  Q&A  >  body text

Is it possible to use if...else... statements in React render functions?

<p>Basically, I have a react component whose <code>render()</code> function body is as follows: (This is my ideal one, which means it doesn't work at the moment)< /p> <pre class="brush:js;toolbar:false;">render(){ return ( <div> <Element1/> <Element2/> // note: logic only, code does not work here if (this.props.hasImage) <ElementWithImage/> else <ElementWithoutImage/> </div> ) } </pre> <p><br /></p>
P粉760675452P粉760675452395 days ago413

reply all(2)I'll reply

  • P粉288069045

    P粉2880690452023-08-24 16:44:43

    There is actually a way to do exactly what the OP asked for. Just render and call the anonymous function like this:

    render () {
      return (
        <div>
          {(() => {
            if (someCase) {
              return (
                <div>someCase</div>
              )
            } else if (otherCase) {
              return (
                <div>otherCase</div>
              )
            } else {
              return (
                <div>catch all</div>
              )
            }
          })()}
        </div>
      )
    }

    reply
    0
  • P粉176980522

    P粉1769805222023-08-24 15:10:18

    Not exactly the same, but there is a workaround. There is a section about conditional rendering in the React documentation that you should take a look at. The following is an example of what you can do using inline if-else.

    render() {
      const isLoggedIn = this.state.isLoggedIn;
      return (
        <div>
          {isLoggedIn ? (
            <LogoutButton onClick={this.handleLogoutClick} />
          ) : (
            <LoginButton onClick={this.handleLoginClick} />
          )}
        </div>
      );
    }

    You can also handle it inside the render function, but before returning jsx.

    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }
    
    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );

    Also worth mentioning is what ZekeDroid brought up in the comments. If you are just checking a condition and don't want to render a specific piece of code that doesn't meet the condition, you can use the && operator.

    return (
        <div>
          <h1>Hello!</h1>
          {unreadMessages.length > 0 &&
            <h2>
              You have {unreadMessages.length} unread messages.
            </h2>
          }
        </div>
      );

    reply
    0
  • Cancelreply