reactjsreact-spring

How can I animate between 2 states in React and see both states during transition


I am have a component that is used to navigate a list, when I select an item I want to slide into another list, but the same component is used and only difference is state. I am struggling to understand how I can see both states (almost like 2 components) during the slide transition

I have created a simplified example of the issue from a fork of one of the react-spring examples

https://codesandbox.io/s/affectionate-morning-1rdw6

by clicking forward and back a slide transition occurs but the state changes immediately for both the leave animation and the enter animation. I would like to keep current state for leave and new state for enter.

I would also like to be able to dynamically change the direction


Solution

  • The problem is that during the transition you only see the current object in the leaving and the entering element. It is because you use the state instead the item property of the transition. Let the useTransition handle the state change, it knows which element leaves and which enters:

        {transitions.map(({ item, props, key }) => {
          return (
            <animated.div key={key} style={{ ...props, background: pages[item].background }}>
              {pages[item].text}
            </animated.div>
          )
        })}
    

    The direction change is almost works as it is in the comment. Make sure the condition in the ternary operation match the direction value. For example if you set the direction to 1 and 0 (instead of 1 and -1) then your original condition should work.

      from: { opacity: 0, transform: `translate3d(${currentState.direction ? '200%': '-200%'},0,0)` },
      enter: { opacity: 1, transform: 'translate3d(0%,0,0)' },
      leave: { opacity: 0, transform: `translate3d(${currentState.direction ? '-200%': '200%'},0,0)` },
    

    https://codesandbox.io/s/distracted-lamport-6pkup?file=/src/index.js