2

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.

3Dos
  • 3,210
  • 3
  • 24
  • 37

1 Answers1

5

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

Rodney Hawkins
  • 404
  • 3
  • 7
  • Thank you very much, now I understand better how `react-spring` works! – 3Dos Aug 06 '18 at 09:11
  • No problem @3Dos, "composite keys" aren't well documented. Sometimes keys need the unique value and then a property for their change / velocity in sequence. – Rodney Hawkins Aug 06 '18 at 09:16