Add a class to the HTML <body> tag with React?

后端 未结 5 658
广开言路
广开言路 2021-01-30 16:57

Im making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

I could do this the old jQuery

5条回答
  •  你的背包
    2021-01-30 17:08

    Actually you don't need 2 functions for opening and closing, you could use document.body.classList.toggle

    const [isOpen, setIsOpen] = useState(false)
    useEffect(() => {
      document.body.classList.toggle('modal-open', isMobileOpen);
    },[isOpen])
        
    
    

提交回复
热议问题