Java Scripts/React.js

Hook in React - useScroll

HobbyCoding 2023. 10. 7. 09:14
728x90

note) <h1 style={{ position: "fixed", color: y > 100 ? "red" : "blue" }}>Hi</h1> 와 같이 style 에서는 대괄호를 2개 사용한다 {{}}

 

note)  scroll event 를 감지하여 <h1> element 의 색을 변경(Blue -> Red)시키고 있다.

 

 

import { useState, useEffect } from "react";

export 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 function App() {
  const { y } = useScroll();

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

note) 위는 아래의 교육과장을 이수하면서 정리한 것이다.

https://nomadcoders.co/react-hooks-introduction/lobby?utm_source=free_course&utm_campaign=react-hooks-introduction&utm_medium=site