Framer Motion 정리

Updated:

Framer Motion

API

Framer for API 도큐먼트


Install & Import



npm install framer-motion

import { motion } from "framer-motion"

export const MyComponent = ({ isVisible }) => (
    <motion.div animate= />
)



usage



기본적인 용법은 상위 import에 나온것과 동일하며, 만약 styled-components와 같이 사용할 때는 아래와 같이 코드를 작성한다.

const Box = styled(motion.div)`
  width: 200px;
  height: 200px;
  background-color: white;
  border-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
`;
  animation이 튕기는 것은 tansition의 type이 spring때문 tween으로 변경하자
   아래로 나오는 것은 damping : 0 무저항
<Box
  initial= //애니메이션 초기 스타일
  animate=
  transition=
></Box>


variants


motion의 prop으로 준 스타일들을 객체로 한곳에 모이게 하여 시각적으로 간결하게 보여주게 된다.

해당 코드의 결과물은 동일하지만 variants를 사용한 것이 훨씬 간결하고 깔끔하다.

const myVars = {
  start: { scale: 0 },
  end: { scale: 1, rotateZ: 360, transition: { type: 'spring', damping: 5 } },
};

<Box
  initial= //애니메이션 초기 스타일
  animate=
  transition=
></Box>

<Box variants={myVars} initial="start" animate="end" />

variants의 큰 장점으로는 자식의 효과도 inint(start)와 animate(end)의 키가 동일하다면 부모의 상태 값을 “상속” 받을 수가 있다.

const boxVariants = {
  start: {
    opacity: 0,
    scale: 0.5,
  },
  end: {
    scale: 1,
    opacity: 1,
    transition: {
      type: 'spring',
      duration: 0.5, //지연시간
      bounce: 0.5,
      delayChildren: 0.5,
      staggerChildren: 0.3, //staggerChildren은 자식의 딜레이를 순차적으로 보이게(1s -> 2s -> 3s- >4s)
    },
  },
};

// NOTE: 기본적으로 varitans는 자식의 효과 키(init,end)가 동일 할 경우, 부모의 init,end 효과를 상속 받는다.

const circleVariants = {
  start: {
    opacity: 0,
    y: 120,
  },
  end: {
    opacity: 1,
    y: 0,
  },
};

<Box variants={boxVariants} initial="start" animate="end">
  <Circle variants={circleVariants} />
  <Circle variants={circleVariants} />
  <Circle variants={circleVariants} />
  <Circle variants={circleVariants} />
</Box>;


transition의 orchestration


delayChildren : number : 딜레이 시간 후에 하위 애니메이션이 시작

staggerChildren : number 하위 자식의 애니메이션의 시차를 줄 수 있음, 값이 1초면 (1s -> 2s -> 3s- >4s)

click,hover,drag

해당 박스의 호버의 효과나 클릭 효과를 주고 싶다면 while..로 시작되는 api로 효과를 주면 된다.

whileHover, whileTap,whileDrag 처럼 각각은 호버,클릭,드래그의 효과를 낼 수 있다.

const boxVariants = {
  hover: { scale: 1.4, rotate: 360 },
  click: { borderRadius: '50%', scale: 0.5 },
};

<Box variants={boxVariants} whileHover="hover" whileTap="click" />;


Drag


Drag는 말 그대로 해당 박스를 드래그하여 움직이고 효과를 나타낼 수 있는 api로 element의 속성에 drag 를 추가하면 해당 드래그는 움직이게 된다.

하지만 드래그가 해당 브라우저에서 제약이 없이 움직이는것이 가능하기 때문에 dragConstraints 를 통해 드래그 가능한 영역을 제약합니다.

// 픽셀 이용
<motion.div drag="x" dragConstraints= />;

// ref이용
const MyComponent = () => {
  const constraintsRef = useRef(null);
  return (
    <motion.div ref={constraintsRef}>
      <motion.div drag dragConstraints={constraintsRef} />
    </motion.div>
  );
};

dragSnapToOrigin: 드래그 가장자리에 있는걸 팅겨서 중앙정렬

dragElastic(탄성) : 말 그대로 당기는 힘이라고 보면 된다. 외부 제약 조건에서 허용되는 이동 정도. 0 = 움직임 없음, 1 = 전체 움직임. 기본적으로 0.5로 설정됩니다. 움직임을 비활성화하기 위해 false로 설정할 수도 있습니다.


MotionValue



useMotionValue : motion이 이뤄지는 값에 대한 초기 밸류 값 설정

useTransform(해당값,[input],[output]) : useTransform()는 한 값 범위에서 다른 값 범위로 매핑하여 다른 MotionValue의 output을 변환하는 모션 밸류값을 만든다.

const x = useMotionValue(0);
const scale = useTransform(x, [-335, 0, 335], [2, 1, 0.1]);

<Box
  style= //motionValue로 인하여
/>;



Error


Can’t import the named export ‘Children’ from non EcmaScript module 에러

  • CRA 버전이 4일 경우에 나오는 에러 CRAv4는 EcmaScript module을 받아드리질 못한다.


[해결방법]

CRACO

craco/README.md at master · gsoft-inc/craco

CRACO란 ? Create React App Configuration Override약어로 create-react-app을 위한 쉽고 이해하기 쉬운 configuration 레이어

  1. CRACO를 설치한다. npm install @craco/craco —save
  2. root 경로에서 터미널로 touch craco.config.js 를 하거나 윈도우에서 할 경우 해당 root 폴더에서 파일을 생성한다.
  3. fammer에 이슈로 등록된 게시물에 해당 에러에 대한 craco.config.js 코드 예제를 가져온다.

    module.exports = {
      webpack: {
            configure: {
                module: {
                    rules: [
                        {
                            type: 'javascript/auto',
                            test: /\.mjs$/,
                            include: /node_modules/,
                        },
                    ],
                },
            },
        },
    }
    
  4. package.json으로 들어가 script의 내용을 아래 내용으로 변경해준다.

    /* package.json */
    
    "scripts": {
    -   "start": "react-scripts start",
    +   "start": "craco start",
    -   "build": "react-scripts build",
    +   "build": "craco build"
    -   "test": "react-scripts test",
    +   "test": "craco test"
    }