search

Home  >  Q&A  >  body text

Can if...else... statements be used in React render functions?

Basically, I have a react component and its render() function body is as follows: (This is my ideal component, which means it doesn't currently work)

render(){
    return (
        <div>
            <Element1/>
            <Element2/>

            // note: logic only, code does not work here
            if (this.props.hasImage) <ElementWithImage/>
            else <ElementWithoutImage/>

        </div>
    )
}


P粉020556231P粉020556231416 days ago528

reply all(2)I'll reply

  • P粉985686557

    P粉9856865572023-10-11 18:32:08

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

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

    reply
    0
  • P粉521013123

    P粉5210131232023-10-11 17:33:34

    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 (
        
    {isLoggedIn ? ( ) : ( )}
    ); }

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

    if (isLoggedIn) {
      button = ;
    } else {
      button = ;
    }
    
    return (
      
    {button}
    );

    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 (
        

    Hello!

    {unreadMessages.length > 0 &&

    You have {unreadMessages.length} unread messages.

    }
    );

    reply
    0
  • Cancelreply