Search code examples
javascriptcssreactjsanimationreact-spring

Make text become white upon changing value in react? React-spring?


I have a div, with player score, deaths and assists:

    <div className="liveMatchPlayerScore">
      {data.kill_count}/{data.death_count}/{data.assists_count}
    </div>

Every time the kill or death count changes, I'd like the text to turn a bold white for 3 seconds.

I was thinking of using react-spring for this, specifically useTransitions, but the documentation shows examples using an array of items. I going to put each of the scores in an array, but it seems counterproductive.

Previously i tried wrapping the scores in an "Spring" component from react-spring but that only animated the scores on their initial render - not when they update.

How can I make the kill_count and death_count become white for 3 seconds upon changing value?

Thank you

I used @PeterAmbruzs solution, but i seem to be getting strange numbers. For example in the images below, first the score was 0/0/0 and the first number increased by 1. Instead of becoming 1/0/0, it became 01/0/0. I'm also getting absurdly high numbers for some reason. Does anyone know why this might be happening?

Before What it should be


Solution

  • I have also a solution. I think it is quite simple. First you create a component for the animated numbers. I wrapped it in react.memo to update it only when its property change. You can see it is bold, and red at start, but after 3sec it became normal and black. But you can change the style whatever you want. I added skip property to prevent animation for example for the first render.

    const FadeNumber = React.memo(({ value, skip }) => {
      const style = useSpring({
        from: { color: "red", fontWeight: "bold" },
        to: { color: "black", fontWeight: "normal" },
        delay: 3000
      });
    
      return (
        <animated.span style={{ margin: "10px", ...(skip ? {} : style) }}>
          {value}
        </animated.span>
      );
    });
    
    

    Now there is a trick to reRender the animation at property change. Simly put the value to the key. When the key changes a new component will be created, so the animation will be played again. I added a unique prefix to prevent side effects.

    <FadeNumber skip={kill === 0} key={"a" + kill} value={kill} />
    

    And the whole example:

    https://codesandbox.io/s/react-spring-change-fade-out-j8ebk