728x90
// index.js
import React, { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";
import useScroll from "./useScroll";
const App = () => {
const { y } = useScroll();
return (
<div className="App" style={{ height: "1000vh" }}>
<h1 style={{ position: "fixed", color: y > 100 ? "red" : "blue" }}>
Hello
</h1>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
// useScroll.js
import React, { useEffect, useRef, useState } from "react";
const useScroll = () => {
const [state, setState] = useState({ x: 0, y: 0 });
const onscroll = () => {
setState({ y: window.scrollY, x: window.scrollX });
};
useEffect(() => {
window.addEventListener("scroll", onscroll);
return () => window.removeEventListener("scroll", onscroll);
}, []);
return state;
};
export default useScroll;
스크롤을 내리면 h1태그의 값 색이 변경되게 만드는 코드입니다.
h1태그를 fixed로 스타일 설정을 하고, color를 삼항연산자를 통해서 조건을 줍니다.
window에 "scroll" 이벤트를 달아주고 window.scrollX, window.scrollY를 통해 스크롤 좌표를 가져옵니다.
window.scrollX
window.scroolY
'React' 카테고리의 다른 글
[React] 알림 보내기 (0) | 2021.01.09 |
---|---|
[React] 전체 화면 (0) | 2021.01.09 |
[React] 현재 네트워크 상태 확인 (4) | 2021.01.08 |
[React] 동적 스타일 적용 (2) | 2021.01.08 |
[React] mouseleave (0) | 2021.01.08 |