본문 바로가기
React

[React] Motion 라이브러리 사용하여 스크롤 진행바 (scrollYProgress 사용) 애니메이션 구현하기

by teamnova 2025. 7. 17.
728x90

 

 

안녕하세요 오늘은 리액트의 가장 유명한 애니메이션 라이브러리 중 하나인 Motion (구 Framer Motion) 을 사용하여 애니메이션을 구현해보도록 하겠습니다. 

블로그나 기사를 볼때  전체 분량 중 얼마나 읽고 있는지 progress bar (스크롤 진행바)로 확인하는 기능을 애니메이션으로 구현해보겠습니다. 

 

 

1. Motion 설치하기

먼저 리액트 라이브러리에 Motion 을 설치합니다. 

 

Get started with Motion for React | Motion for React (prev Framer Motion)

Learn Motion for React animation library: Install, animate HTML and SVG elements with spring animations, staggering effects. Complete guide with examples.

motion.dev

 

npm install motion

 

이후 본인이 적용하고자 하는 화면에 해당하는 자바스크립트 파일에 import 해줍니다. (자바 스크립트 기준) 

import * as motion from "motion/react-client"

 

 

 

2. Motion 라이브러리에서 motion 컴포넌트와 useScroll 훅을 가져옵니다. 

해당 import 문은 프로그레스바를 적용하고자 하는 자바스크립트 파일 상단에 추가해줍니다. 

import { motion, useScroll } from "motion/react";

 

 

 

3. App () 함수 내에 스크롤 값을 가져오는 로직을 작성합니다

 

scrollYProgress = 0 ~ 1 사이의 값
0 = 페이지 맨 위
0.5 = 페이지 중간  
1 = 페이지 맨 아래

function App() {
  const { scrollYProgress } = useScroll();
.
.
.

 

scrollYProgress 이외에도 

  scrollY,           // 실제 픽셀 값 (예: 500px)
  scrollXProgress,   // 가로 스크롤 0~1
  scrollX    등을 가져올 수 있습니다. 

 

 

4. motion.div(스크롤 진행바) 스타일 객체 설정 

      <motion.div
        id="scroll-indicator"
        style={{
          scaleX: scrollYProgress,
          position: "fixed",
          top: 0,
          left: 0,
          right: 0,
          height: "10px",
          originX: 0,
          backgroundColor: "#ff0088",
          zIndex: 9999,
          transformOrigin: "0% 50%",
        }}

 

- 스크롤 진행바의 높이(height), 색상(backgroundColor), 위치(position, top, left, right) 등을 정해줍니다. 

- 애니메이션의 속도와 변화를 설정합니다 (scale, originX, transformOrigin) 

 

 

5. 스크롤바가 화면 구성요소 전체를 감싸게 해줍니다.

<div style={{ minHeight: "200vh" }}>
        {" "}
        {/* 충분한 스크롤을 위한 임시 높이 */}
        <Header />
        <Hero />
        <About />
        <ServicesSection />
        <StatsSection />
        <ProjectGallery />
        <BlogSlider />
        <SimpleCounter />
        <SimpleTodo />
        <SimpleCalculator />
        <ThreeDPortfolio />
        <AvatarPortfolio />
        <ParticlePortfolio />
        <Contact />
      </div>

 

 

시연 영상입니다. 

감사합니다