A zero-dependency tiny package that animates a number increment/decrement on value change for a smooth transition;
Live demo demo source : codesandbox
This package expects
react
version of^16.8.1
( since it usesuseEffect
) as its peer dependency
- Efficient while smooth animation
- Animate the value from previous value (whether its bigger or smaller).
- it uses
requestAnimationFrame
under the hood and does a proper clean up on re-renders. - it will keep a lexical variable automatically to save
previous value
whenvalue
changes, thus you don't to pass aprevValue
; ( what would happen if dont set a previous value in such scenario? the animation always starts from zero on value change which is kinda ugly )
- Install
yarn add react-number-animator
ornpm i react-number-animator
; - Import
import SmoothNumber from "react-number-animator"
; - place it where it is intended like:
<SmoothNumber value={/*sth*/} />
Attention: each release comes with
-compact
version which doesn't includereadme.md
thus half size of regualr package; and can be installed manually using latest version number plus-compact
for exampleyarn add [email protected]
name | type | Required | default | description |
---|---|---|---|---|
value | number | yes | the number you want to show. | |
totalSteps | number | no | 10 |
number of steps to do the animation. the higher the number the longer animation duration. |
className | string | no | optional className to apply on output <span> . |
|
outputFormatter | function | no | (v)=>v |
A function that is applied on each frame output; with this signature: ( val : number ) => string . commonly used to format number in a local formats like showing a comma separated value instead of raw numbers in a banking scenario. |
import SmoothNumber from "react-number-animator";
<SmoothNumber
value={/* somValue */}
totalSteps={15}
/>
Since it uses requestAnimationFrame
under the hood the browser support is the same as requestAnimationFrame browser support itself.
it will fall back to a raw <span>
without any animation just its value.
<span className={className}>{outputFormatter(value)}</span>
About ~2Kb
packed and compact version is about ~1kb