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

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

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

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