Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional rendering (React.js) using logical AND operator (&&) not working

I’m following react.dev docs on conditional rendering and I can’t figure out why conditional rendering using logical AND (&&) operator is not working.

It’s working fine using conditional ternary operator (? :).

The code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"use client";

import { useState } from "react";

export default function Get({ data }) {
    const [toggleShowData, setShowData] = useState(false);

    function handleClick() {
        setShowData(true);
    }

    return (
        <>
            <button onClick={handleClick}>GET average salary</button>

            {/* Conditionally show this element */}
            {toggleShowData ? <h2>{data}</h2> : null} {/* Works */} 
            {toggleShowData ?? <h2>{data}</h2>} {/* Doesn't work */}
        </>
    );
}

>Solution :

It looks like there’s a small typo in your code. You should use the logical AND (&&) operator for conditional rendering, not the nullish coalescing (??) operator. The nullish coalescing operator is used to provide a default value when the left-hand side is null or undefined.

In your context, toggleShowData is a boolean value (true or false), not null or undefined. Therefore, ?? is not suitable for conditional rendering based on a boolean value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading