9
6

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 3 years have passed since last update.

【Next.js】Reactでスクロールを検知する

Last updated at Posted at 2021-06-21

コード

scroll.jsx
import React, {useState, useEffect} from 'react'

const Scroll = () => {
  const [scrollY, setScrollY] = useState(0)

  const handleScroll = () => {
    setScrollY(window.scrollY)
  }

  useEffect(()=> {
    window.addEventListener('scroll', handleScroll )
  }, [])

  return (
    <>
      { scrollY }
    </>
  )
}

export default Scroll

解説

    window.addEventListener('scroll', handleScroll )

ここでイベントリッスンさせて、

  const handleScroll = () => {
    setScrollY(window.scrollY)
  }

関数handleScrollを呼び出すだけ。

9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?