Search code examples
javascriptreactjsreact-spring

React-spring animation only works at first render


I try to animate new entries in an array as they appear with react-spring It works quite fine at the first render but then doesn't animate when updated

Here's a code sandbox where I reproduced the issue with an interval : https://codesandbox.io/s/01672okvpl

import React from "react";
import ReactDOM from "react-dom";
import { Transition, animated, config } from "react-spring";

import "./styles.css";

class App extends React.Component {
  state = { fake: ["a", "b", "c", "d", "e", "f"] };

  fakeUpdates = () => {
    const [head, ...tail] = this.state.fake.reverse();
    this.setState({ fake: [...tail, head].reverse() });
  };

  componentDidMount() {
    setInterval(this.fakeUpdates, 2000);
  }

  componentWillUnmount() {
    clearInterval(this.fakeUpdates);
  }

  render() {
    const { fake } = this.state;
    return (
      <div className="App">
        {fake.map((entry, index) => (
          <Transition
            native
            from={{
              transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
            }}
            to={{ transform: "translateY(0)" }}
            config={config.slow}
            key={index}
          >
            {styles => <animated.div style={styles}>{entry}</animated.div>}
          </Transition>
        ))}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I tried with Spring and Transition with the same result.


Solution

  • Your problem is because your Key is not updating. Since you are replacing key of 0 with key of 0, it think it has already applied the transition.

    When changing the key to be ${entry}_${index}, it'll update they key to 'a_0', then 'f_0' which are unique and different, and therefore trigger the effect you want.

    entry alone as a key does not work either, since it already exists in the DOM, so it'll not re-render the transition.

    <Transition
      native
      from={{
        transform: `translateY(${index === 0 ? "-200%" : "-100%"})`
      }}
      to={{ transform: "translateY(0)" }}
      config={config.slow}
      key={`${entry}_${index}`}
    >
    

    Check it here https://codesandbox.io/s/kkp98ry4mo