Reputation: 11986
I'm trying to modify a CSS variable contained in :root{}
. I have tried two options:
componentDidMount(){
A)
if (typeof window !== "undefined" ) {
console.log("typeof window: ",typeof document)
let document = document.documentElement;
this.setState({document})
}
B)
if (typeof document !== "undefined" ) {
console.log("typeof document: ",typeof document)
let document = document.documentElement;
this.setState({document})
}
}
they both returns:
_document is undefined
How make this work? any hint would be great, thanks
Upvotes: 0
Views: 481
Reputation: 3392
Try changing your variable declaration from document to something else, e.g.
let doc = document.documentElement;
I think your declaration is getting hoisted (see: https://medium.freecodecamp.org/what-is-variable-hoisting-differentiating-between-var-let-and-const-in-es6-f1a70bb43d) so when you actually log typeof document
it actually refers to to your let document =
and not the global document
What your code actually looks like is:
if (typeof window !== "undefined" ) {
let document;
console.log("typeof window: ",typeof document) // when this looks for document it is going to look in the current scope which is the one defined above, which is undefined at the moment
document = document.documentElement;
this.setState({document})
}
Upvotes: 3