Reputation: 41
I am trying to get the scroll position using the following code:
useEffect (()=>{
document.addEventListener("scroll", e => {
let scrolled = document.scrollingElement.scrollTop;
if (scrolled >= 5){
setPos("moved")
} else {
setPos("top")
}
})
},[])
Typescript complains about the document.scrollingElement.scrollTop saying that it is possibly null. How do I avoid this error and keep typescript happy?
Upvotes: 1
Views: 1099
Reputation: 5534
Just do a null
check
useEffect(() => {
document.addEventListener("scroll", e => {
if (document.scrollingElement !== null) {
const scrolled = document.scrollingElement.scrollTop;
if (scrolled >= 5) {
setPos("moved")
} else {
setPos("top")
}
}
})
}, [])
Upvotes: 0
Reputation: 465
I find a null
check guard clause the best way.
useEffect (()=>{
document.addEventListener("scroll", e => {
let scrolled = document.scrollingElement.scrollTop;
if (scrolled === null) {
return;
}
if (scrolled >= 5){
setPos("moved")
} else {
setPos("top")
}
})
},[])
Upvotes: 0
Reputation: 19059
There are at least two ways.
document.addEventListener("scroll", e => {
if (!document.scrollingElement) {
return;
}
let scrolled = document.scrollingElement.scrollTop;
...
});
document.addEventListener("scroll", e => {
let scrolled = document.scrollingElement!.scrollTop;
...
});
Upvotes: 2