React.js: Conditional Rendering

February 3, 2021

Table of Contents


React.js Conditional Rendering

One feature of React.js is the ability to hide or display sections (rendering) of the application based on the values of your Component variables or a Props parameter.


On this first example we can display either the ComponentA or the ComponentB based on the value of the props.show_component parameter, which is being evaluated on a if statement.


import React from "react";

function Sample1(props) {
    let component = '';

    if (props.show_component == 'A') {
        component = <ComponentA />;
    } else if (props.show_component == 'B') {
        component = <ComponentB />;
    }

    return (
        <>
            <h1>Sample1</h1>
            {component}
        </>
    );
}

function ComponentA() {
    return <div>This is Component A</div>;
}

function ComponentB() {
    return <div>This is Component B</div>;
}

function App() {
    return (
        <>
            <Sample1 show_component="A" />
        </>
    );
}

export default App;

On this second example we also use the props.show_component parameter but with a React.js expression in the following form: { condition && <Component /> }


import React from "react";

function Sample2(props) {
    return (
        <>
            <h1>Sample2</h1>
            {props.show_component == 'A' &&
                <ComponentA />
            }
            {props.show_component == 'B' &&
                <ComponentB />
            }
        </>
    );
}

function ComponentA() {
    return <div>This is Component A</div>;
}

function ComponentB() {
    return <div>This is Component B</div>;
}

function App() {
    return (
        <>
            <Sample2 show_component="B" />
        </>
    );
}

export default App;

On this third example we use an onChange event to dynamically trigger the display of either the ComponentA or the ComponentB.


import React, { useState } from "react";

function Sample3() {
    const [state, setState] = useState('');

    function handleChange(event) {
        setState(event.target.value);
    }

    return (
        <>
            <h1>Sample3</h1>
            <select onChange={handleChange}>
                <option value="">Select an option:</option>
                <option value="A">Show Component A</option>
                <option value="B">Show Component B</option>
            </select>

            {state == 'A' &&
                <ComponentA />
            }
            {state == 'B' &&
                <ComponentB />
            }
        </>
    );
}

function ComponentA() {
    return <div>This is Component A</div>;
}

function ComponentB() {
    return <div>This is Component B</div>;
}

function App() {
    return (
        <>
            <Sample3 />
        </>
    );
}

export default App;

Live Demo

See a live demo of the above code on StackBlitz here.