React 17.0.2 Functional Component Only Plays CSS Animation on First Render

I'd like to be able to display text feedback to a user after they answer a question and then fade out the text each time they answer. I'm trying a very simple situation to start out with where I play static feedback after every question. The text between the div is displayed and then fades after the initial rendering of the component but on subsequent renders the text is not displayed and the animation does not occur (I'm using Chrome). I can confirm the component is being re-rendered with Chrome Dev Tools after each cycle and I can see the text in the DOM. I'm using forwards so that at the end of the animation the text will stay invisible. The problem I'm trying to solve is why does the animation only occur after the first render cycle and what do I need to do in order to animate each time the component renders? Other details are that the app uses Redux and all components are functional.

Here's a sandbox that shows what the issue looks like. In this case I passed in props to the feedback component to force it to re-render. Each time you type into the text input it forces the feedback component to re-render (which I confirmed by logging to the console) but the animation only plays on the first render.

https://codesandbox.io/s/reactcssanimationissue-zwc6l?file=/src/UserFeedBack/UserFeedBackComponent.js

    import React from "react";
    import classes from "./AnswerFeedBackComponent.module.css";
    
    const AnswerFeedBackComponent = () => {          
      
        return (
            <div className={classes.CorrectAnswer} >Correct!</div> 
         );    
    }
    export default AnswerFeedBackComponent;
---
.CorrectAnswer{
    color:green;
    font-weight: bold;
    animation: fade 3s linear forwards;
    opacity: 1;
}

@keyframes fade {
    0% {
        opacity: 1;
    }
    100%{
        opacity: 0;
    }
}


Read more here: https://stackoverflow.com/questions/66994606/react-17-0-2-functional-component-only-plays-css-animation-on-first-render

Content Attribution

This content was originally published by Jason Shiffler at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: