Skip to content
Advertisement

How to apply classList.toggle(“active”) in reactjs

How to apply classList.toggle("active") in reactjs. i create a two buttons and give onclick function togglePopup and define it at top. but i’m confused how to apply document.getElementById('popup-1').classList.toggle("active")in react. i apply this method in javaScript and i don’t know how it is work in react?

Popup.jsx

const Filter = () => {
    const togglePopup = () => {
    document.getElementById('popup-1').classList.toggle("active")
    }
    return (
        <>
<button className='p-3 border bg-blue-400'>click</button>
            <div className="popup" id="popup-1">
                <div className="overlay"></div>
                <div className="content">
                    <div className="close-btn" onClick={togglePopup}>&times;</div>
                    <h1 className='text-2xl font-bold'>title</h1>
                    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Non debitis officia neque nostrum, perspiciatis sed quaerat veritatis numquam, explicabo dolorum aliquam illo dolor at nemo maxime consequatur facilis magni laudantium! Ipsa eveniet quam, illum quos laudantium a placeat temporibus dolores libero pariatur quibusdam atque impedit magnam nam ipsum, rerum sapiente?</p>
                </div>
            </div>

Popup.css

.popup .overlay{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
    height: 100vh;
    background:rgba(0, 0, 0, 0.7);
    z-index: 1;
    display: none;
}
.popup .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 450px;
    height: fit-content;
    z-index: 2;
    text-align: center;
    padding: 20px;
    box-sizing: border-box;
}

.popup .close-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    width: 30px;
    height: 30px;
    background: #222;
    color: #fff;
    font-size: 25px;
    font-weight: 600;
    line-height:30px;
    text-align:center;
    border-radius: 50%;
    cursor: pointer;
}

.popup:active .overlay{
    display: block;
}
.popup:active .content{
    transition: all 300ms ease-in-out;
    transform: translate(-50%, -50%) scale(1);

}

Advertisement

Answer

You should not be querying or manipulating the DOM from React. If you want to toggle a class have your button update your component’s state and then render the markup according to that state.

function MyComponent () {
  const [active, setActive] = useState(false);

  return (
    <div className={active ? 'active' : ''}>
      <button onClick={() => setActive(!active)}>Toggle</button>
    </div>
  )

}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement