Conditional Rendering

I. Conditional Rendering

The output of a Functional Component can be determined based on its properties.

For example:

function Feature(props){
    if (props.active == true){
        return <h1>This feature is active</h1>
    }
    else{
        return <h1>This feature is not active</h1>
    }

}

ReactDOM.render(
    <Feature active = {true}/>,
    document.getElementById("root")
)

So,

  • if the active = {true}, it’ll render “This feature is active”
  • if the active = {false}, it’ll render “This feature is not active”

We can also write the Functional component in one line:

function Feature(props){
    return <h1>This feature is {props.active? "active" : "not active"}</h1>
}

ReactDOM.render(
    <Feature active = {true}/>,
    document.getElementById("root")
)

II. Preventing Rendering

The output of a Functional Component can be prevented from rendering.

For example:

function Feature(props){
    if(props.active == false){
        return null
    }
    else {
        return <h1>This feature is active</h1>
    }
}

ReactDOM.render(
    <Feature active = {true}/>,
    document.getElementById("root")
)

So,

  • if the active = {true}, it’ll render “This feature is active”
  • if the active = {false}, nothing will show

We can also use the && operator:

function Feature(props){
    return (
        props.active && <h1>This feature is active</h1>
    )
}
ReactDOM.render(
    <Feature active = {true}/>,
    document.getElementById("root")
)

Explanation With the && operator, true and expression will be evaluate as true, whereas false and expression will be evaluate as false. So,

  • if the active = {true}, it’ll render “This feature is active”
  • if the active = {false}, nothing will show