4
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

コード

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を呼び出すだけ。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
4
Help us understand the problem. What are the problem?