Dynamic Class Assignment in React with Template Literals

Dynamic Class Assignment in React with Template Literals

Sometimes, when we’re shaping a React component, it feels a bit like smoothing soft folds of fabric — logic here, a touch of style there — and the way classes attach themselves becomes part of that quiet craft. Template literals keep that flow gentle and flexible.


What Are Template Literals?

Template literals, introduced in ES6, let you embed expressions inside strings using backticks (`). It’s a simple tool, but it dissolves a lot of friction.

const mode = "dark";
const classString = `button ${mode}`; // "button dark"

In React, this makes combining static and dynamic classes feel natural.


Dynamic Classes in React

React uses className instead of class, and template literals give us a clean way to blend the two worlds.

function Button({ mode }) {
return (
<button className={`button ${mode}`}>
Click Me
</button>
);
}

How It Works

  • button is the always-there foundation.
  • mode drifts in depending on props.
  • Your component stays readable — like a small breath of clarity.

A Gentle Example: Trip Button

Imagine a little trip component, switching between states. Template literals keep it playful and tidy.

function TripButton({ status }) {
return (
<button className={`trip-button ${status}`}>
🦅 Eagle's {status}!
</button>
);
}
  • <TripButton status="landed" />class="trip-button landed"
  • <TripButton status="flying" />class="trip-button flying"

A simple pattern, but it keeps your components expressive without the clutter.


Tips for Cleaner Components

  • Provide fallbacks — avoid undefined drifting into your classes.
function Button({ mode }) {
return (
<button className={`button ${mode || "default"}`}>
Click Me
</button>
);
}
  • Keep logic simple — for bigger conditions, use clsx or a helper.
  • CSS Modules work well too — just blend the pieces:
import styles from './Button.module.css';

function Button({ mode }) {
  return (
    <button className={`${styles.button} ${styles[mode]}`}>
      Click Me
    </button>
  );
}

Why Template Literals Feel Good

  • Clean.
  • Flexible.
  • Beginner-friendly.
  • No extra libraries.

Sometimes the simplest patterns are the ones that let your components breathe.


Wrapping Up

Dynamic class assignment with template literals keeps React components readable and expressive without overthinking the structure. A little clarity, a soft touch… and suddenly the UI feels lighter.

If your next project needs a small, gentle pattern for styling, this one holds up beautifully.