user21149140
user21149140

Reputation: 3

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

Upvotes: 0

Views: 109

Answers (1)

Yilmaz
Yilmaz

Reputation: 49661

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");
    };
  }, []);

Upvotes: 0

Related Questions