Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Switching classes on button press is just state

The first dark mode toggle I built in React, I built the way I had built them in plain JavaScript for years. I grabbed the document body and called classList.toggle('dark') on it, and it worked. Click, dark. Click again,

The first dark mode toggle I built in React, I built the way I had built them in plain JavaScript for years. I grabbed the document body and called classList.toggle('dark') on it, and it worked. Click, dark. Click again, light. It shipped, and then a user reported the toggle losing its setting. They would switch to dark, click anything that re-rendered the page, and the page snapped back to light while the button still said dark. The class and the state had disagreed, and the class lost, because React re-renders from state, not from anything painted onto the DOM by hand.

The rule: in React, a class is not something you apply, it is something state decides. The button does not change its own class, it changes a value, and the render picks the class that matches. Treat className as a function of state, and every toggle, tab bar, and theme picker gets simpler, because there is only ever one thing to update.

the boolean version

The simplest case is one button with two looks, and a boolean in useState is all the state it needs. The className reads the boolean with a ternary, and the label reads the same boolean, so the look and the words can never disagree.

ThemeToggle.tsx

import { useState } from 'react';

function ThemeToggle() {
  const [dark, setDark] = useState(false);

  return (
    <button
      type='button'
      onClick={() => setDark((prev) => !prev)}
      className={dark ? 'btn btn-dark' : 'btn'}
    >
      {dark ? 'Switch to light' : 'Switch to dark'}
    </button>
  );
}

The button never touches the DOM itself. setDark flips the boolean, React re-renders, and the className expression picks the other string. The label changes in the same render, which is the part I like most. Two things that used to drift apart, the style and the text, now come from the same value, so they stay in sync for free.

the multi-way switch

A boolean only gives you two looks. A theme picker, a layout switcher, or a tab bar has three or more, so the state holds a string instead, and the class comes from a small lookup. This is the version to reach for most often, because adding a fourth option means adding one line to the lookup and one button, and nothing else changes.

ThemePicker.tsx

import { useState } from 'react';

const themes = {
  berry: 'rounded-xl p-5 bg-[#C70D52] text-white',
  forest: 'rounded-xl p-5 bg-[#2F6B4F] text-white',
  midnight: 'rounded-xl p-5 bg-[#1e1f26] text-white',
} as const;

type Theme = keyof typeof themes;

function ThemePicker() {
  const [theme, setTheme] = useState<Theme>('berry');
  const [pop, setPop] = useState(false);

  const cardClass = themes[theme] + (pop ? ' ring-4 ring-amber-300 shadow-lg' : '');

  return (
    <div>
      <div className={cardClass}>
        <h3>Pick a theme</h3>
        <p>The card changes because the state changed.</p>
      </div>
      {(Object.keys(themes) as Theme[]).map((key) => (
        <button
          key={key}
          type='button'
          onClick={() => setTheme(key)}
          className={theme === key ? 'swatch swatch-active' : 'swatch'}
        >
          {key}
        </button>
      ))}
      <button type='button' onClick={() => setPop((prev) => !prev)}>
        {pop ? 'Remove the pop' : 'Make it pop'}
      </button>
    </div>
  );
}

Try it: the theme picker, live
Try it live on nayemalam.com.

Pick a theme, then hit make it pop. The line under the card shows the exact className string the render produced, so you can watch the state turn into a class in real time. Nothing in the demo touches the DOM directly. Every change is a setTheme or a setPop, and the class follows.

the shortcut that invents a class named false

The version that bites people is the shortcut. Template literals make it tempting to write the condition with &&, and it looks right until you open devtools and find a class literally named false. When dark is false, the expression evaluates to false, the template literal turns it into the string "false", and the button gets a class that matches nothing in your CSS. It does nothing visible, which is why it survives in codebases for months, and it confuses the next person who inspects the element.

the-false-class.ts

// The shortcut: when dark is false, this renders class="btn false".
const withShortcut = `btn ${dark && 'btn-dark'}`;

// The ternary: the class list only ever holds real class names.
const withTernary = `btn ${dark ? 'btn-dark' : ''}`;

The ternary is two characters longer and only ever holds real class names, so it is the version to write by default. The && shortcut has a safe home, though, and it is the next section.

a tiny helper for when the list grows

Once a component has three or four conditional classes, nested ternaries in the JSX get hard to read, and that is when the join belongs in a tiny helper. It takes the class names, drops the false ones, and joins what is left with spaces. Six lines, reused across projects, and it is the place where && becomes safe, because false values disappear before they reach the DOM.

cx.ts

function cx(...parts: (string | false | undefined)[]) {
  return parts.filter(Boolean).join(' ');
}

const classes = cx('btn', dark && 'btn-dark', large && 'btn-large');

The rule is simple. The base class stays outside the condition, always on, and only the switching part is conditional. A boolean gets a ternary, three or more options get a lookup, and a long list gets the helper. The DOM is left alone, because the moment a class is painted by hand, the next render wipes it.

The class is a render of state, not a thing you apply. When a button looks wrong, check the state first, because the DOM only shows what state said. A ternary for two looks, a lookup for three or more, a helper when the list grows, and the class follows the state every time.

Originally posted on nayemalam.com/blog.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.