Introduction

Here's how to add classes dynamically to elements in React.

Example - Using States

import React, { useState } from "react"

const [hidden, setHidden] = useState(true)

const toggleHidden = () => {
  setHidden(!hidden)
}

render() {
  return (
    <div>
      <button onClick={toggleHidden}>TOGGLE HIDDEN</button>

      <div className={`toggle-div ${hidden ? "hidden" : ""}`}>
        <h1>I'm inside the hidden div</h1>
      </div>
    </div>
  );
}

NOTE: There are a couple different ways to set the classes.

  1. With JSX expression className={"toggle-div" + (hidden ? " hidden" : "")}
  2. With template literals: className={`toggle-div ${hidden ? "hidden" : ""}`}