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
"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.