본문 바로가기

개발자 페이지/React JS, Next JS

React JS / Typescript / framer-motion 02

728x90
반응형

Framer-motion에서 Slider를 구현하면서 결국 인도 IT 유투버에게 가르침을 받아 다음과 같은 코드를 완성하였다.

 

아래 문제의 그 Slider... 

 

양방향으로 slide가 넘어가게끔 되어있는데 left 갔다가 right로 빠지면 exit 애니메이션이 의도한 바와는 반대X축으로 이동하는 문제를 나타나서 며칠동안 앓고있었다.

 

<AnimatePresence /> 의 custom ={} Variants값이다.

const rowVariants = {
  hidden: (direction: number) => ({
    x: direction > 0 ? window.outerWidth : -window.outerWidth,
  }),
  visible: {
    x: 0,
  },
  exit: (direction: number) => ({
    x: direction > 0 ? -window.outerWidth : window.outerWidth,
  }),
};

아래 direction은 원래 Boolean값이었다가 Number값으로 바꿨다.

const [direction, setDirection] = useState(0);
  const [index, setIndex] = useState(0);
  const [leaving, setLeaving] = useState(false);

  const increaseIndex = () => {
    if (data) {
      if (leaving) return;
      setDirection(1);
      toggleLeaving();
      const totalMovies = data.results.length - 1;
      const maxIndex = Math.floor(totalMovies / offset) - 1;
      setIndex((prev) => (prev === maxIndex ? 0 : prev + 1));
    }
  };
  const decreaseIndex = () => {
    if (data) {
      if (leaving) return;
      setDirection(-1);
      toggleLeaving();
      const totalMovies = data.results.length - 1;
      const maxIndex = Math.floor(totalMovies / offset) - 1;
      setIndex((prev) => (prev === 0 ? maxIndex : prev - 1));
    }
  };

AnimatePresence 및 custom값 참조

 <AnimatePresence
              custom={direction}
              initial={false}
              onExitComplete={toggleLeaving}
            >
              <Row
                custom={direction}
                variants={rowVariants}
                initial="hidden"
                animate="visible"
                exit="exit"
                transition={{ type: "tween", duration: 1 }}
                key={index}
              >

 

728x90