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

后端 未结 5 577
广开言路
广开言路 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:26

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

提交回复
热议问题