0

Adding and removing classes to elements in React

I’m a complete newb with React but basically I’ve been trying to make it so that a container goes from hidden to visible when you click a button. Usually I’d just do an eventListner and add.classList or remove.classList but I can’t find the equivalent to that in react ? I’ve tried figuring it out with useState and everything but I feel like I’m just overlooking something simple. I would really appreciate some help it’s been like hours and my tiny brain is gonna explode

Eternity
  • 3
  • 1
  • Please post the code you're having trouble with, and review [how to ask](https://stackoverflow.com/help/how-to-ask) to make sure your question is appropriate for Stackoverflow. Each part of your question has [many](https://stackoverflow.com/questions/36209432/how-to-dynamically-add-a-class-to-manual-class-names) [duplicate](https://stackoverflow.com/questions/62421592/how-to-toggle-boolean-state-in-react-and-typescript) questions which are easy to search for, so your specific problem will be easier to answer with a minimal reproducible example. – Andy Ray Jun 02 '23 at 04:38

1 Answers1

1

I would recommend adding a condition to render the element/component instead of using classes.

const [visible, setVisible] = useState(false);

return (
  <div>
    <button onClick={() => setVisible(!visible)}>toggle</button>
    {visible && <span>hello</span>}
  </div>
);
Gohchi
  • 434
  • 3
  • 12