Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Flow possible null value with document.body.classList.add

I have a react component where I change the html body class. The class is being added in componentDidMount and removed in componentWillUnmount. I am using Flow for type checking. When I run Flow I get the following error:

src/modules/homepage/HomePage.js:27
 27:         document.body.classList.remove('homepage')
                           ^^^^^^^^^ property `classList`. Property cannot be accessed on possibly null value
 27:         document.body.classList.remove('homepage')
             ^^^^^^^^^^^^^ null

Can anyone suggest how to suppress this error or what would be the recommended approach?

Thank you

like image 980
Julius Koronci Avatar asked Dec 19 '22 09:12

Julius Koronci


1 Answers

This error is exactly what it sounds like. Property classList cannot be accessed on possibly null value. (document.body)

document.body is not defined until the document.readyState is interactive. You can similarly wait for the domcontentready or load events, but you're probably already doing that since you're rendering React components.

In practice, flow is kind of annoying here because in a browser environment once document.body is defined, it stays defined.

Here are some easy solutions:

You can use an invariant function: invariant(document.body); // throw an error if document.body does not exist yet document.body.classList.remove('homepage');

Or put the statement in an if block:

if (document.body) {
    document.body.classList.remove('homepage') 
}
like image 142
Matt Oates Avatar answered Dec 31 '22 02:12

Matt Oates