简体   繁体   中英

React CSS Keyframes - animate when state removes component from DOM

I'm struggling to use CSS Keyframes with React.

I can get them to work when the component is mounted but when the component is unmounted the CSS transitions don't get a chance to animate before the state removes it from the DOM.

I'm not keen on doing this with a JS library when it feels like there should be a way to do this with good old CSS.

I've got a codepen that I put together to show what I've got so far. https://codesandbox.io/s/react-hooks-usestate-forked-dhvu7?file=/src/styles.css

At the end of the animation I'd like the component to be unmounted I don't want it to stay in the dom.

Thanks in advance.

You can use css keyframe and use onAnimationEnd event handler to trigger state change after the animation is finished. Also you can add style={{ animationFillMode: "forwards" }} to the node to preserve the CSS properties of the last keyframe before removing it from the DOM.

Example:

{removeDom && (<button
      style={{ animationFillMode: "forwards" }}
      className="some animation class"
      onAnimationEnd={()=>setRemoveDom(true)}
 />)}

For anyone else wanting a solution this article got me to where I wanted to be https://czaplinski.io/blog/super-easy-animation-with-react-hooks/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM