I defined a userRef to set scrollTop for a Div tag:
const listRef = useRef<HTMLDivElement>(null);
but I can't set scrollTop with this code:
listRef.scrollTop = listRef.current.scrollHeight;
returns this error: Object is possibly 'null'
CodePudding user response:
Set default value
const listRef = useRef<HTMLDivElement>(document.createElement('div'))
Use optional operater
listRef.scrollTop = current?.scrollHeight || 0
CodePudding user response:
window.scrollTo({ top: 0, behavior: 'smooth' })
CodePudding user response:
First initialize this state:
const [showButton, setShowButton] = useState(false);
Then add this inside ur useEffect hook:
window.addEventListener("scroll", () => {
if (window.pageYOffset > 300) {
setShowButton(true);
} else {
setShowButton(false);
}
});
And heres the scrollToTop function outside the useEffect hook:
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
};
Then just paste this html part inside ur react return loop:
{showButton && (
<button onClick={scrollToTop} className="back-to-top">^
</button>)}
Pls upvote this answer :)
CodePudding user response:
Try to use Optional chaining to make typescript only access the property if parent property doesn't have null or undefined value.
Also you probably forgot to use current property with ref.
const listRef = useRef<HTMLDivElement | null>(null);
listRef.current?.scrollTop = listRef.current?.scrollHeight;
