본문 바로가기

Java Scripts/React.js

Hook in React - useFadeIn

728x90

note) fade in 효과가 element 안에서 나타나게 하기 위하여 useEffect 를 사용하였다.

 

note) spread operator <h1 {...fadeInH1}>Hello</h1> 을 이용하여 쉽게 setting 을 할 수 있었다. 이것을 사용하지 않으면 다음과 같이 복잡하게 사용해야 한다.
<h1 ref={fadeInH1.ref}  style={fadeInH1.style} >Hello</h1>

 

note) 맨처음 Hello 가 천천히 나타나고 5초 있다가 Test Test2 Test3 Test4 가 천천히 나타난다.

 

 

import { useRef, useEffect } from "react";

export const useFadeIn = (duration = 1, delay = 0) => {
  if (typeof duration !== "number" || typeof delay !== "number") {
    return;
  }
  const element = useRef();
  useEffect(() => {
    if (element.current) {
      const { current } = element;
      current.style.transition = `opacity ${duration}s ease-in-out ${delay}s`;
      current.style.opacity = 1;
    }
  }, []);
  return { ref: element, style: { opacity: 0 } };
};

export default function App() {
  const fadeInH1 = useFadeIn(1, 2);
  const fadeInP = useFadeIn(5, 10);

  return (
    <div className="App">
      <h1 {...fadeInH1}>Hello</h1>
      <p {...fadeInP}>Test Test2 Test3 Test4</p>
    </div>
  );
}

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

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

 

'Java Scripts > React.js' 카테고리의 다른 글

Hook in React - useAxios  (0) 2023.09.28
Hook in React - useFullScreen  (0) 2023.09.28
Hook in React - useConfirm  (0) 2023.09.28
Hook in React - useHover  (0) 2023.09.28
Hook in React - useClick  (0) 2023.09.28