LoginSignup
5
7

More than 3 years have passed since last update.

Reactで複数要素に動的にクリック→スクロールする(createRef, useRef)

Posted at

Reactでクリック→スクロールする方法について

Reactで『クリック→該当部分までスクロール』を行う場合、以下のようにcreateRefを使用することがありました。

App.tsx
const ref = createRef<HTMLDivElement>()

ここで定義したrefをスクロールさせたい箇所に渡して、

App.tsx
const handleJump = useCallback(() => {
  ref!.current!.scrollIntoView({ behavior: "smooth" })
}, [ref])

クリック時にスクロールするよう関数を定義する。すると以下のようにクリック→スクロールができます。

sample.gif

ソースコードは以下を参照いただければ幸いです。
CodeSandbox

ですが、これだとスクロール箇所が増える度に、ユニークなrefを定義していく必要があるので、
複数の要素に動的にスクロールさせることを検討しました。

結論

以下がソースコードです。
CodeSandbox

App.tsx
type Item = {
  title: string;
  background: string;
  service: string;
  otherContent?: boolean;
};

const items: Item[] = [
  { title: "コンテンツ1", background: "skyblue", service: "サービス1" },
  { title: "コンテンツ2", background: "yellow", service: "サービス2" },
  { title: "コンテンツ3", background: "green", service: "サービス3", otherContent: true }
];

↑のような配列のデータがある場合、

App.tsx
  const pageRef = useRef(items.map(() => createRef<HTMLDivElement>()));

  const scrollToView = (id: number) => {
    pageRef.current[id]!.current!.scrollIntoView({ behavior: "smooth" });
  };

↑のコードのように
- mapを使ってrefの配列を作り
- 関数(scrollToView)の引数にはidを受け取る

とすることでrefを何度も定義せずに動的にクリック→スクロールをさせることができました!

wiita.gif

参考

5
7
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
5
7