Toggling CSS Classes in React


Uncategorized

Updated Aug 24th, 2021

Is “classList.add()” and toggle and remove a thing in React? Really for the DOM so only if using useRef.

Instead we manage with state, a handler function and some conditional JS in the “className={}” part of the element.

What I did in an early version of my portfolio site:

<div className={${`styles.menuIcon_top} ${isOpen ? menuIcon_top__close : ""}`}></div>

Note: This is how I added two classes in CSS modules although I think you can just put multiple classes in one template literal.

Also Note: I used empty quotes but the article below uses NULL and you can also use the double ampersand strategy as well. Not sure if there is a performance difference here or a best practice.

Important to know the “add/remove/toggle” CSS class technique is an alternative to conditionally showing a different component.

This article here has some examples

Side Note: When using CSS Modules, or Styled Components it is redundant to create BEM-style class naming since this typically ends up in very long class names. Take advantage of the CSS specificity by using shorter class names.


Top