iTranslated by AI
The Most Reliable Way to Implement Auto-Scroll in React
I want to scroll to the bottom of the HTML when the screen loads
Hi, I'm Dove. I needed to implement auto-scrolling for a work project, so I considered a few different methods.
- Using
scrollToBottom()insideuseEffect(oruseLayoutEffect) withreact-scroll. - Using a list library called
react-windowand callingscrollToItem()to the last item duringuseEffect. - Placing a
divtag at the end of the list, getting itsref, and callingref.current.scrollIntoView()insideuseLayoutEffect.
Please refer to this article regarding useRef as well:
Conclusion: Using scrollIntoView with ref is best
Minimum Implementation
const List = () => {
const scrollBottomRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
// This is the TypeScript syntax. For JavaScript:
// if(scrollBottomRef && scrollBottomRef.current) {
// scrollBottomRef.current.scrollIntoView()
// }
scrollBottomRef?.current?.scrollIntoView();
}, []);
const items: string[] = [];
return (
<div>
{items.map(item => (<div>{item}</div>))}
<div ref={scrollBottomRef}/>
</div>
)
}
After fetching data
const List = () => {
const [isLoading, setIsLoading] = useState(false);
const [items, setItems] = useState<string[]>([]);
const scrollBottomRef = useRef<HTMLDivElement>(null);
// Data fetching
useEffect(() => {
// Flag to avoid setting state after unmount.
let isUnmounted = false;
const load = async () => {
const items = await axiosLikeLibrary.get('https://example.com/items');
if(!isUnmounted){
setItems(items)
}
};
load();
return () => {
isUnmounted = true;
}
}, []);
// Auto-scroll after fetching
useLayoutEffect(() => {
// This is the TypeScript syntax. For JavaScript:
// if(scrollBottomRef && scrollBottomRef.current) {
// scrollBottomRef.current.scrollIntoView()
// }
scrollBottomRef?.current?.scrollIntoView();
}, []);
const items: string[] = [];
return (<>
{isLoading ? (
<div>Loading...</div>
) : (
<div>
{items.map(item => (<div>{item}</div>))}
{/* div for scrolling to the bottom ↓ */}
<div ref={scrollBottomRef}/>
</div>
)}
</>)
}
Why other options were not suitable
Using scrollToBottom() inside useEffect (useLayoutEffect) with react-scroll
This is difficult. The animate scroll function of react-scroll did not work inside useEffect. In the end, I tried waiting for rendering by adding some delay with setTimeout inside useEffect before scrolling, but that approach didn't work well either because the time it takes for rendering to complete varies depending on the length of the list.
Here is a related issue:
Maybe the element isn't declared in the tree yet.
I'm not exactly sure, but it seems that the tree might not be declared yet withinuseEffect.
Using react-window to scrollToItem() to the last item during useEffect
This also worked. Details are here:
However, using react-window just for scrolling seemed like overkill, so I decided against it.
Discussion
scrollIntoView 知らなかったです...
ありがとうございます。
読んでたら、typo を見つけてしまいました...