"If" shorthand on react component

I have a simple logic for check which menu is active.

I’m using:

const [activeMenu, setActiveMenu] = useState("0");

for the state.

and using if shorthand:

  1. className={activeMenu === "2" && "active"}
  2. className={activeMenu === "1" ? "active" : ""}

but the first one gave me:

react_devtools_backend.js:4026 Warning: Received `false` for a non-boolean attribute `className`.

If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}.

My question is why the first one gave me that warning? but my site is still working like charm.
Why is that say that received false?

>Solution :

if activeMenu is not 2, then className would be false (invalid)

className={activeMenu === "2" && "active"}

with this

className={activeMenu === "2" ? "active" : ""}

if activeMenu is not 2, then className would be an empty string (valid)

So, it’s basically as the error says. className is not a boolean attribute.

run the code below in console, it’s basically the same thing as your code. It will return false

false && "active" !== null

Leave a Reply