React: Programmatically Add/Remove CSS Classes

Updated: March 3, 2023 By: A Goodman Post a comment

This succinct, practical article shows you how programmatically add/remove CSS classes to/from an element in React. We can get the job done without installing any third-party libraries.


You can add/remove single or multiple classes to/from an element with an event handler function or by using the useRef hook.

With an event handler function:

// define the event handler function
const buttonClickHandler = (e) => {

// set onClick or other event props on your element
<button onClick={buttonClickHandler}>I AM A BUTTON</button>

With the useRef() hook:

/* Fefine a ref */
const kindaCodeRef = useRef();

/* Tie the ref with a certain element */
<div ref={kindaCodeRef}></div>

/* Add and Remove many classes at once */
kindaCodeRef.current.classList.remove('class-1', 'class-2', 'class-3');
kindaCodeRef.current.classList.add('class-4', 'class-5', 'class-6');

You can also toggle a class name like so:


For more clarity, see the complete, working example below.


App Preview

The tiny React project we’re going to build presents a text input and box that contains a message. A name entered into the text input is considered valid if its length is equal to or more than 3 characters. The color of the box can be one of the following:

  • Gray: If the input is empty
  • Red: If the name provided is from 1 to 3 characters
  • Blue: If the name entered is valid

Another component of our React app is a button that can change its background color on click.

Here’s the demo:

The Code

1. Initialize a new React project by performing the command below:

npx create-react-app kindacode-example

As of now, we’ll focus on these 2 files: src/App.js and src/App.css. Other files will be intact.

2. Replace all of the default code in your src/App.js with the following (you can see explanations in the comments):

// src/App.js
import { useRef, useState } from 'react';
import './App.css';

function App() {
  const messageRef = useRef();

  const [message, setMessage] = useState(
    'If your name is less than 3 characters, it will be rejected.'

  // this function will be triggered when the input changes
  const inputChangeHandler = (e) => {
    const enteredText =;

    // In the beginning or when the user deletes everything, use the default style
    if (enteredText.length === 0) {
        'If your name is less than 3 characters, it will be rejected.'
      messageRef.current.classList.remove('message--error', 'message--success');
    } else if (enteredText.length < 3) {
      setMessage('Your name is too short.');
    } else {
      setMessage('Your name is valid.');
      messageRef.current.classList.remove('message--default', 'message--error');

  // this function is called when the button gets clicked
  const buttonClickHandler = (e) => {

  return (
      <div className='container'>
          <h2>Welcome to</h2>
            placeholder='Enter your name'
        <div ref={messageRef} className='message message--default'>

        <button onClick={buttonClickHandler} className='button button--light'>
          Toggle My Color

export default App;

3. Empty your src/App.css file, then add the following:

.container {
  width: 80%;
  margin: 50px auto;

/* classes related to the text input and the message */
.input {
  width: 300px;
  padding: 10px 10px;
  border: 1px solid #bbb;
  border-radius: 5px;

.message {
  margin-top: 20px;
  padding: 20px;
  border-radius: 5px;

.message--default {
  background-color: #f1f1f1;
  color: #333;

.message--error {
  background: #e53935;
  color: white;

.message--success {
  background: #1565c0;
  color: white;

/* classes related to the button */
.button {
  margin-top: 50px;
  padding: 12px 30px;
  font-size: 16px;
  border: none;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  cursor: pointer;

.button--light {
  background: #eee;
  color: #666;

.button--dark {
  background: #666;
  color: #fff;

4. Boot it up and go to http://localhost:3000 to see the result.


You’ve learned the technique to add and remove CSS classes in React without using any third-party packages. If you want to consolidate your programming skills and explore more new and interesting things in the modern React world, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles