2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactで同時に、一緒にスクロールをしたい。

Posted at

結論

const Tables = () => {
  const rightEl = useRef()
  const leftEl = useRef()

  const handleScroll = (isLeft) => {
    isLeft
      ? (rightEl.current.scrollTop = leftEl.current.scrollTop)
      : (leftEl.current.scrollTop = rightEl.current.scrollTop)
  }

  return (
    <>
      <LeftTable ref={leftEl} onScroll={handleScroll}/>
      <RightTable ref={rightEl} onScroll={handleScroll}/>
    </>
  )
}

解説

ReactではuseRefを使うことで要素を取得することができます。そして、スクロール量もその取得した要素と一緒に得られるので片方のスクロール量をもう片方のスクロール量にすることでスクロールを同期させることができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?