How to toggle class in the nested component in React and JavaScript?

Sometimes, we want to toggle class in the nested component in React and JavaScript.

In this article, we’ll look at how to toggle class in the nested component in React and JavaScript.

How to toggle class in the nested component in React and JavaScript?

To toggle class in the nested component in React and JavaScript, we can use the classnames library.

To install it, we run npm i classnames.

Then we use it by writing:

import React from "react";
import classNames from "classnames";

export default function App() {
  const [active, setActive] = React.useState(false);
  const cx = classNames({ green: active });

  return (
    <>
      <style>{`.green { background-color: green }`}</style>
      <button onClick={() => setActive((a) => !a)}>toggle</button>
      <section className={cx}>hello world</section>
    </>
  );
}

to create the cx variable by calling classNames with an object that has the class name as the key and the condition of which it’s applied as the value.

When active is true, the green class is applied.

And we add a button to toggle the green class by setting onClick to a function that calls setActive to toggle the value of active.

Conclusion

To toggle class in the nested component in React and JavaScript, we can use the classnames library.