react-scroll
react-scroll copied to clipboard
Can't scroll on component mount
I have the following function to scroll to the bottom of the container
const scrollChatToBottom = useCallback(() => {
animateScroll.scrollToBottom({
containerId: "event-chat-messages",
});
}, []);
And I want to execute that function on the component mount
useEffect(() => {
scrollChatToBottom();
}, [
scrollChatToBottom,
]);
But it's not working, is there a reason to that happen?
Should most likely work.
Could you provide a Plunkr/Codepen demonstrating the issue?
@fisshy Sure! I created a sandbox in order to demonstrate the issue
I'm not really sure why it doesn't work on initial mount. but providing a ref solves it.
import React, { useRef, useEffect } from "react";
import { animateScroll } from "react-scroll";
import "./styles.css";
export default function App() {
const { ref } = useRef();
useEffect(() => {
animateScroll.scrollToBottom({
container: ref,
duration: 2000,
smooth: true
});
}, [ref]);
return (
<div id="big-container" ref={ref}>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Maybe the element isn't declared in the tree yet.
Yepp, could be.
Hey there, @fisshy! I don't think this issue is solved.
Should be resolved internally within the lib - otherwise everywhere we use this we'll have to add a ref
or setTimeout
- which is neither documented nor practical.
If you want we could submit a PR fixing this issue.
Yes, I was a bit fast to close it, sorry.
You both are more then welcome to make a PR. Would be cool to make something like “useScroll” which resolves after the three is updated.
@fisshy How about this? I solved the problem with this.
import { useEffect, useRef } from "react";
import { scroller } from "react-scroll";
const containerRef = useRef(null);
useEffect(() => {
if (containerRef && containerRef.current) {
scroller.scrollTo("event-chat-messages", {});
}, [containerRef.current]);
<div ref={containerRef}>
<div id="event-chat-messages"></div>
</div>
@ru88s It's a good workaround, I think I actually have a PR solving this, but I've forgotten to merge it.
https://github.com/fisshy/react-scroll/pull/435
I should probably merge this.
@fisshy I understand now. Thank you very much. I'm having trouble with the process after the DOM load is complete, so please merge.