Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

document.body.classList.add/remove not working as expected

document.body.classList.add/remove not working as expected

When I call add(), it only adds the class attribute to the body element, but it doesn’t attach any value to it. Meanwhile, if I manually add the class to the body element and then call remove(), nothing happens

useEffect(() => {
        document.body.classList.add('overflow-hidden')

        return (
            document.body.classList.remove('overflow-hidden')
        )
    }, [])

This is the code currently. I expected the class ‘overflow-hidden’ to be added to the body element when the component is first rendered and I expected the class ‘overflow-hidden’ to be removed from the body element was the component was closed

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you have issue with the return. it has to return a function and this function will be called when the component is unmounted:

useEffect(() => {
    document.body.classList.add("overflow-hidden");
    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading