0

How to animate React Component with react-spring library depend on props updating

I found this https://codesandbox.io/s/xpqq0ll5nw and want to implement the same with hooks

const Counter = ({quantity}) => {
  const animation = useSpring({
    transform: 'scale(1)',
    from: { transform: 'scale(1.2)' },
  });

  return (
    <animated.span style={animation}">
      {quantity}
    </animated.span>
  )
}
sliim35
  • 25
  • 4

1 Answers1

0

Your Counter component is about right. The key here is the 'key' property. When the counter changes it alternates between 1 and 0. And each time the key changes React assign a new Counter component instance instead the old one repeating the initial animation of the Counter component.

  class App extends Component {
    state = { count: 0 };
    increment = () => this.setState({ count: this.state.count + 1 });
    render() {
      return (
        <Fragment>
          <button onClick={this.increment}>Update!</button>
          <Counter key={this.state.count % 2} quantity={this.state.count} />
        </Fragment>
      );
    }
  }

Here is the whole example: https://codesandbox.io/s/jjyp6p0yl9

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36