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
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')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With