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
<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 */}
</>
);
}
</code>
<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 */}
</>
);
}
</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 */}
</>
);
}