[React] 스크롤 작동으로 스타일 변경하기

쿼카쿼카·2022년 8월 16일
0

React / Next

목록 보기
26/34

코드

import React, {useState, useRef, useEffect} from 'react'

function useScroll() {
  const [state, setState] = useState({
    x: 0,
    y: 0,
  });

  function onScroll() {
    setState({y: window.scrollY, x: window.scrollX});
  }

  useEffect(() => {
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, [])

  return state;
}

export default function App() {
  const {y} = useScroll();

  return (
    <div style={{height: '100vh'}}>
      <h1 style={{position: 'fixed', color: y > 100 ? 'red' : 'blue'}}>Hi</h1>
    </div>
  )
}

배운점

  • scroll은 state를 객체 형태로 받는 게 편하다
  • 객체를 return하면 const {y} = useScroll(); 로 받는다.
  • 사실 스크롤이 안 생겨서 확인은 못 했다^^
profile
쿼카에요

0개의 댓글