Skip to content

Instantly share code, notes, and snippets.

@inorganik
Last active July 15, 2024 02:07
Show Gist options
  • Save inorganik/2cf776865a4c65c12857027870e9898e to your computer and use it in GitHub Desktop.
Save inorganik/2cf776865a4c65c12857027870e9898e to your computer and use it in GitHub Desktop.
Using CountUp.js in React
import { useEffect, useRef } from 'react'
// playground: https://stackblitz.com/edit/react-ts-nv5fxe?file=App.tsx
export default function App() {
// create a ref and declare an instance for each countUp animation
const countupRef = useRef(null);
let countUpAnim;
// useEffect with empty dependency array runs once when component is mounted
useEffect(() => {
initCountUp();
}, []);
// dynamically import and initialize countUp, sets value of `countUpAnim`
// you don't have to import this way, but this works best for next.js
async function initCountUp() {
const countUpModule = await import('countup.js');
countUpAnim = new countUpModule.CountUp(countupRef.current, 1000);
if (!countUpAnim.error) {
countUpAnim.start();
} else {
console.error(countUpAnim.error);
}
}
// in the jsx use the ref attribute to bind the element to `countupRef`
return (
<>
<h1 ref={countupRef} onClick={() => {
// replay animation on click
countUpAnim.reset();
countupAnim.start();
}}>0</h1>
</>
);
}
@abolfazlchaman
Copy link

Came in handy, many thanks for your time <3

@SawHtutNaing
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment