简体   繁体   中英

How to apply classList.toggle("active") in reactjs

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

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>

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM