How to dynamically add a css class in React

Hey

I have been trying to toggle a border on a button in react using onClick. I know for vanilla Js i can use a function with

element.classList.toggle('border')

getting the element variable from the Dom.
However whenever i try to use this same thing in onClick in JSX is does not work.
Any clarity on how i can achieve this would be much appreciated

const Button =  () => {
  const [className, setClassName] = React.useState("foo");

  return (
    <button className={className} onClick={() => setClassName("bar")}>Clicking this will change the class name from "foo" to "bar"</button>
  );
};

This just changes the class from foo to bar. To toggle it, or add/remove classes you’ll need to write a handler function that uses the setClassName function to do whatever you want it to do. Or just show/hide the border directly:

const Button =  () => {
  const [showBorder, setShowBorder] = React.useState(false);

  return (
    <button style={{ border: showBorder ? "10px solid pink" : "none" }} onClick={() => setShowBorder(!showBorder)}>Clicking this will show or hide the border</button>
  );
};
1 Like

Thank you so much this is really helpful

1 Like