📌

任意の位置まで自動スクロールする

2023/02/21に公開

サンプルコード

import { useRef } from 'react'

import Button from '@mui/material/Button'

export const Scroll = () => {
  // scroll state
  const scrollmRef = useRef<HTMLDivElement>(null)

  // scroll
  const scroll = () => {
    scrollmRef?.current?.scrollIntoView()
  }

  return (
    <>
      {/* contents
      ・
      ・
      ・
      ・ */}
      {/* 自動でスクロールしたい場所 */}
      <div ref={scrollmRef} />
      {/* contents
      ・
      ・
      ・
      ・ */}
      <Button onClick={() => scroll()}> ボタンを押したらスクロールします </Button>
    </>
  )
}

このコードではボタン押下時に指定の場所へ移動するようになっているが、
effectを使用することで、ある操作が行われた時に自動でスクロールさせるということもできる。(その機能は未実装)


資料を探し終わった後、実際に実装するのは10分で完了

参考資料

https://zenn.dev/dove/articles/be3fff0e84729d
https://ramble.impl.co.jp/415/
https://blog.usize-tech.com/vertical-scroll-by-react/

Discussion