코드
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(); 로 받는다.
- 사실 스크롤이 안 생겨서 확인은 못 했다^^