0

I'm trying to animate from/ to another component when I press a button. I am using useTransition from react-spring. When doing that, the animation works, however, my height shifts when the animation is ongoing.

I've tried putting different positions on the animated.div (from react-spring) and setting a fixed height on it. But nothing seems to work.

// The state that keeps track on the current component
const [index, setIndex] = useState(0);

// My function that updates my state
const onClick = useCallback(() => setIndex(state => (state === 0 ? 1 : 0)), []);

// The transition I'm using
const transitions = useTransition(index, p => p, {
    from: {
        opacity: 0,
        transform: index === 0 ? "translate3d(-100%,0,0)" : "translate3d(100%,0,0)"
    },
    enter: { opacity: 1, transform: "translate3d(0%,0,0)" },
    leave: {
        opacity: 0,
        transform: index === 0 ? "translate3d(50%,0,0)" : "translate3d(-50%,0,0)"
    }
});

// My components
const pages = [
    ({ style }) => <animated.div style={style}>1</animated.div>,
    ({ style }) => <animated.div style={style}>2</animated.div>
]

// How I'm rendering out the component
{transitions.map(({ item, props, key }) => {
    const Page = pages[item];
    return <Page key={key} style={props} />;
})}

The animation works, however the height shifts. I've made a small codesandbox that demonstrates it here: https://codesandbox.io/s/dry-thunder-ydkg8

But in my actual code, my height looks like this: https://youtu.be/7cGLOK7fCco

Martin Nordström
  • 5,779
  • 11
  • 30
  • 64

1 Answers1

0

You need to use position:absolute on the two elements to avoid that shift (and add a position:relative on one of the parent container) -(see the updated codesandbox) :

const pages = [
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "red"
        }}
      >
        First page
      </animated.div>
    ),
    ({ style }) => (
      <animated.div
        style={{
          ...style,
          position: "absolute",
          top: "0",
          backgroundColor: "blue"
        }}
      >
        Second page
      </animated.div>
    )
  ];

Gaël S
  • 1,598
  • 6
  • 15