3

Following simple component from the official examples:

import {useSpring, animated} from 'react-spring'

function App() {
  const props = useSpring({opacity: 1, from: {opacity: 0}})
  return <animated.div style={props}>I will fade in</animated.div>
}

Question

How do I animate the fadeIn-effect (or any other animation) again for example when I click on a button or when a promise is resolved?

oemera
  • 3,223
  • 1
  • 19
  • 33

1 Answers1

6

You can basically make two effect with useSpring and an event.

  1. You can change the style for example the opacity depending on the state of an event.

  2. You can restart an animation on state change. The easiest way to restart is to rerender it.

I created an example. I think you want the second case. In my example I rerender the second component with changing its key property.

const Text1 = ({ on }) => {
  const props = useSpring({ opacity: on ? 1 : 0, from: { opacity: 0 } });
  return <animated.div style={props}>I will fade on and off</animated.div>;
};

const Text2 = () => {
  const props = useSpring({ opacity: 1, from: { opacity: 0 } });
  return <animated.div style={props}>I will restart animation</animated.div>;
};

function App() {
  const [on, set] = React.useState(true);

  return (
    <div className="App">
      <Text1 on={on} />
      <Text2 key={on} />
      <button onClick={() => set(!on)}>{on ? "On" : "Off"}</button>
    </div>
  );
}

Here is the working example: https://codesandbox.io/s/upbeat-kilby-ez7jy

I hope this is what you meant.

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36
  • The example for `Text2` ist exactly what I wanted. Can you explain why it works with `key={on}` ? Also is it possible to do this without creating a seperate component? – oemera Nov 29 '19 at 09:52
  • 3
    It is a trick. I think you are aware, that if you create react components in a loop you must define the key property. React use this to decide during a change which component to update and which to delete. It works on a single component as well. If you change the key it will replaced with a new one. I think you must create a separate component, because you want to restart the useSpring initialisation. I'm not aware simpler solution. – Peter Ambruzs Nov 29 '19 at 10:24
  • I know how keys work, what I didn't know was that you can put one on a single components. Kinda sad that there is no solution without an extra component. Ideally it would be greate if `useSpring` returned a callback for that: `const {props, reanimate} => useSpring(...)`. But maybe that's not even possible. Anyway, your solution is good enough. – oemera Nov 29 '19 at 10:40