Add A Class To The HTML Tag With React?
Answer :
TL;DR use document.body.classList.add
and document.body.classList.remove
I would have two functions that toggle a piece of state to show/hide the modal within your outer component.
Inside these functions I would use the document.body.classList.add
and document.body.classList.remove
methods to manipulate the body class dependant on the modal's state like below:
openModal = (event) => { document.body.classList.add('modal-open'); this.setState({ showModal: true }); } hideModal = (event) => { document.body.classList.remove('modal-open'); this.setState({ showModal: false }); }
With the new React (16.8) this can be solved with hooks:
import {useEffect} from 'react'; const addBodyClass = className => document.body.classList.add(className); const removeBodyClass = className => document.body.classList.remove(className); export default function useBodyClass(className) { useEffect( () => { // Set up className instanceof Array ? className.map(addBodyClass) : addBodyClass(className); // Clean up return () => { className instanceof Array ? className.map(removeBodyClass) : removeBodyClass(className); }; }, [className] ); }
then, in the component
export const Sidebar = ({position = 'left', children}) => { useBodyClass(`page--sidebar-${position}`); return ( <aside className="..."> {children} </aside> ); };
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]) <button onCLick={()=> setIsOpen(!isOpen)}>Toggle Modal</button>
Comments
Post a Comment