Search code examples
reactjsanimationflexboxcarouselframer-motion

How to create a carousel in React.js and Framer Motion


I want to create an animated carousel with Framer Motion in React.js. The idea is to see the two divs changing horizontally after each other when a button is clicked.

When I do that with AnimatePresence, the first div shrinks, because the second div is created at the same time. Here you can see the code sandbox.

I tried already to use exitBeforeEnter prop but it doesn't work for my use case. I want to see the two changing divs together. With exitBeforeEnter, this is not possible.

I also tried to set the position of the Slide component to absolute. The problem with that is, that all the flex properties of the container get lost. The container doesn't adapt it's high depending on the Slide component.

How can I do it then?


Solution

  • I solve it using a grid:

          <div
            class="container"
            style={{
              height: 400,
              display: "grid"
            }}
          >
    
        ...
    
        <motion.div
          style={{
            gridArea: "1 / 1 / 2 / 2",
            ...
          }}
        >