Ad

How To Make Animation For Div In React Using React-spring When Hiding?

- 1 answer

as for react with react-spring hiding to make an animation for a div when click on button {aa}?

https://codesandbox.io/s/silly-feistel-j1snp

  const props = useSpring({config: { duration: 1250 },opacity: 1, from: {opacity: 0}});
  const foo =() =>{
    setAa(!aa)
  }
  return (
    <div className="App">

      <div onClick={()=>foo()}>aa</div>
      <br/>
      {aa &&
      <animated.div  style={props}>I will fade in</animated.div>}   
    </div>````
Ad

Answer

You need to use useTransition instead of useSpring:

  const transitions = useTransition(aa, null, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });

And in the render method :

  return (
    <div className="App">
      <div onClick={() => foo()}>aa</div>
      <br />
      {transitions.map(
        ({ item, key, props }) =>
          item && (
            <animated.div key={key} style={props}>
              I will fade in
            </animated.div>
          )
      )}
    </div>
  );

Working example: https://codesandbox.io/s/modest-pine-2dr7s

Docs: https://www.react-spring.io/docs/hooks/use-transition

Ad
source: stackoverflow.com
Ad