코딩/Framer

[lib] Framer - motion 라이브러리 사용방법 학습.

카슈밀 2024. 6. 30. 12:51
반응형

https://www.framer.com/motion/

 

Documentation | Framer for Developers

An open source, production-ready motion library for React on the web.

www.framer.com

 

설치방법

npm install framer-motion

 

사용방법

그냥 html을 사용하는 방법과 같습니다.

 

motion.(element)로 사용합니다.

import { motion } from "framer-motion"

export const MyComponent = () => (
  <motion.div
    initial={{ opacity: 0, scale: 0.5 }}
    animate={{ opacity: 1, scale: 1 }}
    transition={{ duration: 0.5 }}
  />
)

initial - 초기값,

animatie - 행동값

Transition - 사용시간

 

해당 내용으로 적용됩니다.

 

공식문서에도 적혀있듯이 여러 내용이 있지만, 중요한 내용을 정리해봅시다.

  • AnimatePresence
    Dom에서 렌더링시 Dom삭제할때, 애니메이션없이 사라집니다.
    이를 막기위해서 해당 내용으로 조건부 렌더링이 적용될때,
    조건 미충족될 경우 사라지는 Dom을 지연삭제하게 하여, 애니메이션 렌더링 후 삭제되게 만들어줍니다.
  • exits
    해당 속성은 dom을 삭제할때, 적용되는 css입니다.
  • mode
    • sync: - 이벤트가 전환될경우 바로 적용됩니다.
    • wait: - 이벤트가 전환될때 기다리면서 변합니다.
    • popLayout: - 팝업 이벤트 사용할때 사용합니다.

      해당 내용은 모두 조건부 렌더링 같은 새로 생성되거나 내용이 변경될때 사용합니다.

      https://www.framer.com/motion/animate-presence/
 

AnimatePresence | Framer for Developers

Animate components when they're removed from the React tree.

www.framer.com

 

단일 조건 렌더링의 내용입니다.

import { motion, AnimatePresence } from "framer-motion"

export const MyComponent = ({ isVisible }) => (
  <AnimatePresence>
    {isVisible && (
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
      />
    )}
  </AnimatePresence>
)

 

멀티플 조건 렌더링 경우 key이 적용되어야 합니다.

export const Notifications = ({ messages }) => (
  <AnimatePresence>
    {messages.map(({ id, content }) => (
      <motion.li
        key={id}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
      >
        {content}
      </motion.li>
    ))}
  </AnimatePresence>
)

 

 

  • useScroll
    스크롤 기능을 매우 편하게 만들어줘서 처리가 어려운 것들을 쉽게 적용하게 해줍니다.
    스크롤 이벤트 값을 자동으로 측정하게 해줍니다.
import { useScroll } from "framer-motion"

const { scrollY } = useScroll()

useMotionValueEvent(scrollY, "change", (latest) => {
  console.log("Page scroll: ", latest)
})

 

  • useTransform
    이게 핵심인데, 배열로 받아서 숫자별, 시간별 변화를 적용할 수 있습니다.
    첫번째 파라미터가 기준값, 2번째가 기준값의 위치별 변화설정, 3번째가 어떻게 변할지를 적용하는 겂니다.
    아래 내용은 y값과 scale이니 스크롤할 경우 상하 위치 이동과 확대되는 변화가 적용됩니다.
import { motion, useScroll, useTransform } from 'framer-motion';

// 대충 컴포넌트 내부
const { scrollY } = useScroll();

const yText = useTransform(scrollY, [0, 200, 300, 500], [0, 0, 50, 300]);
const scaleText = useTransform(scrollY, [0, 300], [1, 1.5]);

return (
	<motion.div style={{ scale: scaleText, y: yText }}>
    	{children}
    </motion.div>
);

 

  • variants atturibute
    이건 그냥 props와 같은 속성입니다.
    상위에서 설정할 경우 하위태그에서도 이를 자동 적용이 되고, 사용할 수 가 있습니다.
const action = {
	visible: { opacity: 1, scale: 1 }, // 배열도 적용이 됩니다. visible: { opacity: 1, scale: [0.8, 1.2, 1] },
    hidden: { opacity: 0, scale: 0.5 }
}

<motion.div
	variants={action}
    initial="hidden"
    animatie="visible"
>
	<motion.span
    	variants={action}
    >
    	text
    </motion.span>
</motion.div>

 

  • layouts
    이걸 제대로 이해되기가 좀 어려운 내용인데, 간단하게 말하면 animate 이벤트가 발생할 경우 해당 이벤트가 발생하는 내용을 자연스럽게 이동하게 해준다고 보면 된다.
    ul>li의 갯수가 변경될 경우 자연스럽게 내려가거나 위로 올라간다거나
    tab기능에서 tab간 전환시 자연스럽게 슥슥 바뀌는 기능을 구현할때 사용된다.
    단 layoutId라는 속성값을 적용해야 Dom의 변화를 감지한다, 그리고 Id값을 동적값으로 적용할 경우
    예를 들어 숫자 카운팅 내용이 변경될시 바뀌었다는 이벤트가 작동됨. 


    li 갯수가 변하고 이를 동적으로 카운팅하는 게 있다면, 이걸 이용해서 바뀌었다는걸 알려주는 animate를 만들수 있습니다.
    https://codesandbox.io/p/sandbox/framer-motion-layout-animations-snxgv?from-embed=
 

https://codesandbox.io/p/sandbox/framer-motion-layout-animations-snxgv?from-embed=

 

codesandbox.io

 

 

728x90