0

Been busting my head against this for a week now. I'm using react-spring to create a transition animation between pages. Those pages are defined by a switch case that is called within the render of a React Component.

I made a quick oversimplifeid sandbox with the odd behaviour:

https://codesandbox.io/s/50y5kkljz4

Most of this code is a simulation of my more complex stack. Looking for any suggestions and what i'm missing.

Is this a bug from react-spring?

Am I doing something that a no no in React?

Is it even possible to animate between (switch) cases?

Things to try:

  1. [Line 71] Comment out keys from the Transition Component. See what result.
  2. [Line 74] Comment out the leave prop from the Transition Component. See result.

Full API reference for react-spring

Thanks in advance!

1 Answers1

0

You need to make a subtle adjustment. You're passing to <Transition> a function in the form:

function(styles) {
  return <div styles={styles}>getComponent(...)</div>;
}

You're deferring resolving what exact component that is until the function is evaluated.

As <Transition> re-renders, the previous function, and the current function, will both evaluate to the same component, given by the current index, and you see this effect.

Instead, what you can do is:

    <Transition
      keys={this.state.index}
      from={{ opacity: 0 }}
      enter={{ opacity: 1 }}
      leave={{ opacity: 0 }}
    >
      {wrap(this.selectContent(type))}
    </Transition>

where:

const wrap = cmp => styles => <div style={styles}>{cmp}</div>

i.e. given an actual component, return a function that takes the react-spring styles and places them on a wrapper div.

I hope this helps!

Dan
  • 9,912
  • 18
  • 49
  • 70