Is it possible to use if...else... statements in React render functions?
P粉760675452
P粉760675452 2023-08-23 18:27:14
0
2
382

Basically, I have a react component whose render() function body is as follows: (This is my ideal one, which means it doesn't work at the moment)< /p>

render(){ return ( 
// note: logic only, code does not work here if (this.props.hasImage) else
) }


P粉760675452
P粉760675452

reply all (2)
P粉288069045

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
) } })()}
) }
    P粉176980522

    Not exactly the same, but there is a workaround. There is a section about conditional rendering in theReact documentationthat 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.

    }
    );
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!