본문 바로가기
끄적끄적/리액트 공부 - 노마드 코더

[리액트 공부] 노마드 코더, 실전형 리액트 Hooks 10개 - useScroll

by 레일라오리덕 2021. 4. 30.
728x90

노마드 코드의 무료 강의 웹사이트는 아래 주소로 가면 된다.

nomadcoders.co/

 

[예제 코드]

 

import { StrictMode, useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom";

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 state;
};

const App = () => {
  const { y } = useScroll();
  return (
    <div className="App" style={{ height: "1000vh" }}>
      <h1 style={{ position: "fixed", color: y > 100 ? "red" : "blue" }}>Hi</h1>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

[강의 설명]

 

728x90

댓글