[React] React 애니매이션

정호·2024년 5월 2일
0

TIL

목록 보기
16/16

모달창에 애니매이션 넣기

CSS
애니메이션 slide-up은 모달이 나타날 때 위로 슬라이드되면서 페이드 인되는 효과@keyframes을 생성하여 적용

코드

Header.jsx

import { useState } from "react";

import NewChallenge from "./NewChallenge.jsx";

export default function Header() {
  const [isCreatingNewChallenge, setIsCreatingNewChallenge] = useState();

  function handleStartAddNewChallenge() {
    setIsCreatingNewChallenge(true);
  }

  function handleDone() {
    setIsCreatingNewChallenge(false);
  }

  return (
    <>
      {isCreatingNewChallenge && <NewChallenge onDone={handleDone} />}

      <header id="main-header">
        <h1>Your Challenges</h1>
        <button onClick={handleStartAddNewChallenge} className="button">
          Add Challenge
        </button>
      </header>
    </>
  );
}

Modal.jsx

import { createPortal } from "react-dom";

export default function Modal({ title, children, onClose }) {
  return createPortal(
    <>
      <div className="backdrop" onClick={onClose} />
      <dialog open className="modal">
        <h2>{title}</h2>
        {children}
      </dialog>
    </>,
    document.getElementById("modal")
  );
}

index.css


@keyframes slide-up {
  0% {
    transform: translateY(30px);
    opacity: 0;
  }

  100% {
    transform: translateY(0);
    opacity: 1;
  }
}

.modal {
  top: 10%;
  border-radius: 6px;
  padding: 1.5rem;
  width: 30rem;
  max-width: 90%;
  z-index: 10;
  animation: slide-up 0.3s ease-out forwards;
}

CSS transition, animation의한계

CSS 애니메이션으로 DOM의 요소를 나타나게 할 순 있지만 사라지게 할 순 없다는 없다.

Library: framer-motion

html태그에 motion추가 ex) <motion.div

      <motion.div
        id="box"
        animate={{ x, y, rotate }}
        transition={{
          duration: 0.3,
          // bounce: 0,
          type: "spring",
        }}
      />

motion.layout

<motion.li layout>
      <article className="challenge-item">
        <header>
          <img {...challenge.image} />
          <div className="challenge-item-meta">
            <h2>{challenge.title}</h2>
//
</motion.li>

motion.layout사용하면 자동으로 레이아웃변동 애니매이션 적용 가능

useScroll, useTransform

스크롤 위치와 이를 기반으로 한 요소의 애니메이션을 조작

const { scrollY, scrollX } = useScroll();

ex)


  const yCity = useTransform(scrollY, [0, 200], [0, -100]);
  const opacityCity = useTransform(
    scrollY,
    [0, 200, 300, 500],
    [1, 0.5, 0.5, 0]
  );
 <motion.img
          style={{ opacity: opacityCity, y: yHero }}
          src={cityImg}
          alt="A city skyline touched by sunlight"
          id="city-image"
        />
  • 첫 번째 매개변수는 변환을 적용할 속성(scrollY)
  • 두 번째 매개변수는 입력 범위, [0, 200]
  • 세 번째 매개변수는 출력 범위, [0, -150]

--> 입력 범위에 따라 "hero 이미지의 y 축 위치가 변경
스크롤 위치가 0일 때는 0으로 유지되지만, 200까지 스크롤될 때는 -150까지 이동하게 된다.
따라서 페이지를 스크롤할수록 hero 이미지가 위로 이동하여 화면에서 사라지는 효과를 얻을 수 있다.

profile
열심히 기록할 예정🙃

0개의 댓글