0

This is my code:

render() {
    return (
      <div  className='btndiv'>
        <button className='btn'>Hide</button>
      </div>
    );
}

When I click the button I want the class of the div to change from .btn.div to .btn divhidden, which basically dissapears it from screen.

.btndivhidden{
  display: none
}

I have watched multiple solutions but many of them are too complicated and put way too much code. How can I achieve this the most efficient and short way?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Maxator
  • 53
  • 1
  • 7

3 Answers3

2

You can do something relatively simple like this:

export default function App() {
  const [isVisible, setIsVisible] = useState(true);

  const handleClick = () => setIsVisible(false);

  return (
    <div className={isVisible ? 'btndiv' : 'btndivhidden'}>
      <button className='btn' onClick={handleClick}>
        Hide
      </button>
    </div>
  );
}
rb612
  • 5,280
  • 3
  • 30
  • 68
0

This is not the best way to do this in react, but it gets it work done!! In the beginning I wasn't familiar with the react. So, I used to do these cheap ways to solve things. You can also try this if you feel like react is complicated, just to make yourself familiarize.

const hideClass = () => {
  const elem = document.querySelector(".btndiv");
  elem.classList.replace("btndiv", "btndivhidden");
};
export default function App() {
  return (
    <div className="App">
      <div className="btndiv">
        <button className="btn" onClick={() => hideClass()}>
          Hide
        </button>
      </div>
    </div>
  );
}
0
import React, { useState } from "react";

export default function App() {
  const [isChange, setIsChange] = useState(true);

  const handleChange = () => setIsChange(!isChange);

  return (
    <div className={isChange ? "btndiv" : "btndivhidden"}>
      <button className="btn" onClick={handleChange}>
        Hide
      </button>
    </div>
  );
}
Thaiyalnayaki
  • 148
  • 1
  • 8