iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
⛓️

The Most Reliable Way to Implement Auto-Scroll in React

に公開
2024/02/13
1件

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() inside useEffect (or useLayoutEffect) with react-scroll.
  • Using a list library called react-window and calling scrollToItem() to the last item during useEffect.
  • Placing a div tag at the end of the list, getting its ref, and calling ref.current.scrollIntoView() inside useLayoutEffect.

Please refer to this article regarding useRef as well:
https://zenn.dev/dove/articles/e2d962e9d69e20

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:
https://github.com/fisshy/react-scroll/issues/430

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 within useEffect.

Using react-window to scrollToItem() to the last item during useEffect

This also worked. Details are here:
https://zenn.dev/dove/articles/4649c8e2dc3cd8

However, using react-window just for scrolling seemed like overkill, so I decided against it.

Discussion

yanskunyanskun

scrollIntoView 知らなかったです...
ありがとうございます。

読んでたら、typo を見つけてしまいました...

- const scrollBottomRef = useRef<HTMLDivEelement>(null);
+ const scrollBottomRef = useRef<HTMLDivElement>(null);
1