Typescript 기반 React에서 scroll animation 직접 구현하는 방법

이번 글을 통해 배워갈 내용
- React에서 직접 isVisible 기반 스크롤 애니메이션 구현해 보기
개요
마치 스프링에 롬복처럼
aos는 편리하나 라이브러리를 설치해야 된다는 단점이 있습니다
Nextjs 13으로 업데이트하면서 aos 가 실행이 안 되는 버그가 발생해서
해결책은 찾았으나
https://stackoverflow.com/questions/75379440/the-aosanimation-on-scroll-is-not-working-in-next-13
The AOS(Animation on scroll) is not working in next 13
I Use next 13 , I wanna add AOS library in my app and us it , I installed it , and added it properly to my component, but my component doesn't show and also I don't get any error.here is my Home Page
stackoverflow.com
이러한 불편함을 사전에 방지하기 위해서
최대한 깔끔하게 tailwind로 라이브러리를 직접 구현했습니다
코드
먼저 useIsVisible 훅을 만들었습니다
이 훅을 사용해서 시야에 보이면 animaition이 발동합니다
// useIsVisible.tsx
import { useEffect, useState, RefObject } from 'react';
export function useIsVisible(ref: RefObject<HTMLElement>): boolean {
const [isIntersecting, setIntersecting] = useState(false);
useEffect(() => {
if (!ref.current) {
return;
}
const observer = new IntersectionObserver(([entry]) => {
setIntersecting(entry.isIntersecting);
});
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, [ref]);
return isIntersecting;
}
아래와 같이 훅을 호출합니다
const ref = useRef<HTMLDivElement>(null);
const isVisible = useIsVisible(ref);
<div ref={ref} className={`ease-in duration-700 ${isVisible ? 'opacity-100 scale-95' : 'opacity-25 scale-100'}`}>
호출하는 컴포넌트는 다음과 같습니다
'use client';
import { useRef } from 'react';
import { useIsVisible } from '@/components/hook/useIsVisible';
type IProps = {
colorStr: string;
};
const Hello: React.FC<IProps> = ({ colorStr }) => {
const divRef = useRef<HTMLDivElement>(null);
const isVisible = useIsVisible(divRef);
const visibilityClasses = isVisible ? 'opacity-100 scale-95' : 'opacity-25 scale-100';
return (
<section className="relative container mx-auto h-[500px]">
<div ref={divRef} className={`ease-in duration-700 ${visibilityClasses}`}>
<div className={`${colorStr} text-white h-96 p-10 text-9xl`}>Hello</div>
</div>
</section>
);
};
export default Hello;
시연영상
잘 작동하는 것을 볼 수 있습니다
참조 및 인용
https://www.npmjs.com/package/react-animate-on-scroll
react-animate-on-scroll
React component to animate elements on scroll with animate.css. Latest version: 2.1.7, last published: 8 months ago. Start using react-animate-on-scroll in your project by running `npm i react-animate-on-scroll`. There are 31 other projects in the npm regi
www.npmjs.com
https://www.freecodecamp.org/news/create-scroll-animations-with-framer-motion-and-react/
How to Create Scroll Animations with React, Tailwind CSS, and Framer Motion
Scroll-based animations are triggered when a user scrolls on a webpage. Recently, I built a Scroll Animation with Framer Motion [https://www.aceternity.com/components/container-scroll-animation] that moves grids in uneven directions. This project prompted
www.freecodecamp.org
블로그 추천 포스트
https://codemasterkimc.tistory.com/50
300년차 개발자의 좋은 코드 5계명 (Clean Code)
이번 글을 통해 배워갈 내용 좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋
codemasterkimc.tistory.com
'Javascript > NextJs' 카테고리의 다른 글
| NextJs 14.1.0에서 TailwindCss NotoSans Font 설정하기 (0) | 2024.01.20 |
|---|---|
| Nextjs Tailwind CSS에 다크모드 적용 3분컷 방법 (0) | 2023.04.14 |
| Nextjs Tailwind CSS에 사용자 지정 글꼴 적용하기 23년 최신 방법 (0) | 2023.04.08 |
| Next Js에서 Do not use <img> 오류 해결 하는 2가지 방법 (0) | 2021.08.07 |