-
-
Save zxs-1024/a4eb1040a17f9e7393dde8b0d6b2e865 to your computer and use it in GitHub Desktop.
Using CountUp.js in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment