Search code examples
javascriptreactjsreact-spring

Number showing as NaN


I'm using react-spring to make a component which counts from zero (0) to ten (10) over a 10 second duration:

export default function Counter() {
    const props = useSpring({
        from: { number: 0 },
        to: { number: 10 },
        config: {
            duration: 10000
        } 
    });

    return (
        <animated.h1>
           {props.number}
        </animated.h1>
    )
}

This results in a large floating point number that counts upward when it renders. I now just want to just show the integer value instead of the floating point.

Using:

<animated.h1>
   {props.number.toFixed()}
</animated.h1>

Yields: TypeError: props.number.toFixed is not a function

Using:

<animated.h1>
   {Number(props.number).toFixed()}
</animated.h1>

Renders 'NaN' where the Counter component is.

Where am I going wrong? Thanks in advance!


Solution

  • It looks like props.number is a number but it's not, it's an instance of AnimatedValue from react-spring so you can't apply your typical functions to it and what not.

    I'm pretty sure if you wanna format that number value you can just do something like {props.number.interpolate(number => number.toFixed())}