LoginSignup
0
1

react で smooth scroll 実装

Last updated at Posted at 2023-09-07

reactでスムースにスクロールさせた時のメモ

sample.tsx
import { memo, useRef } from "react";

const sample = () => {
    const ref = useRef<HTMLDivElement>(null);
    
    const scrollToTarget = () => {
        // scrollIntoViewのbehaviorオプションで"smooth"を追加
        ref?.current?.scrollIntoView({ behavior: "smooth" });
    };
    
    return (
        <>
            <button onClick={scrollToTarget}>
              目的地までスムーズにスクロールします
            </button>
            
            // (省略)
            
            // スクロールする要素へref追加
            <div ref={ref}>Target</div>
        </>
    )
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1