Home > OS >  how to change class of a div onclick on react
how to change class of a div onclick on react

Time:11-24

So im learning React and im having a problem, this is my code until now:


  render() {


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

So 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?

CodePudding user response:

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>
  );
}

CodePudding user response:

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>
  );
}

CodePudding user response:

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>
  );
}
  • Related