react-use-count-up
Version:
A React hook with Typescript typings for animating a number counting up
75 lines (74 loc) • 3.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useCountUp = void 0;
var react_1 = require("react");
var easing_functions_1 = require("./easing-functions");
var fps = 60;
var intervalDelay = Math.round(1 / fps * 1000);
var useCountUp = function (_a) {
var start = _a.start, end = _a.end, duration = _a.duration, _b = _a.started, started = _b === void 0 ? true : _b, formatter = _a.formatter, easingFunction = _a.easingFunction;
var _c = (0, react_1.useState)(start), value = _c[0], setValue = _c[1];
(0, react_1.useEffect)(function () {
if (started) {
// determine the easing function to use
var fn_1;
if (typeof easingFunction === 'function') {
fn_1 = easingFunction;
}
else if (easingFunction === 'linear') {
fn_1 = easing_functions_1.linear;
}
else if (easingFunction === 'easeOutExpo') {
fn_1 = easing_functions_1.easeOutExpo;
}
else if (easingFunction === 'easeInExpo') {
fn_1 = easing_functions_1.easeInExpo;
}
else if (easingFunction === 'easeOutQuad') {
fn_1 = easing_functions_1.easeOutQuad;
}
else if (easingFunction === 'easeInQuad') {
fn_1 = easing_functions_1.easeInQuad;
}
else if (easingFunction === 'easeOutCubic') {
fn_1 = easing_functions_1.easeOutCubic;
}
else if (easingFunction === 'easeInCubic') {
fn_1 = easing_functions_1.easeInCubic;
}
else if (easingFunction === 'easeOutQuart') {
fn_1 = easing_functions_1.easeOutQuart;
}
else if (easingFunction === 'easeInQuart') {
fn_1 = easing_functions_1.easeInQuart;
}
else if (easingFunction === 'easeOutQuint') {
fn_1 = easing_functions_1.easeOutQuint;
}
else if (easingFunction === 'easeInQuint') {
fn_1 = easing_functions_1.easeInQuint;
}
else {
fn_1 = easing_functions_1.easeOutExpo; // default
}
var time_1 = 0;
var change_1 = end - start;
var intervalId_1 = setInterval(function () {
// check to see if we're at the end
if (time_1 >= duration) {
setValue(end); // skip the calculation and use the end number directly
clearInterval(intervalId_1); // we don't need the interval anymore
return;
}
// set the new value based on the easing function
setValue(fn_1(time_1, start, change_1, duration));
// increase the time value based on the interval delay
time_1 += intervalDelay;
}, intervalDelay);
// clear the interval on unmount/props change
return function () { return clearInterval(intervalId_1); };
}
}, [start, end, duration, started, easingFunction]);
return formatter ? formatter(value) : value.toFixed(0);
};
exports.useCountUp = useCountUp;