Base Usage
import { h } from "preact"
import { LerpNum } from "@/comps/varia/lerpnum"
import { useRandomBetween } from "@/comps/varia/utils"
export function LerpNumDemo() {
const num1 = useRandomBetween(50, 500, 1000, 3000)
const num2 = useRandomBetween(5, 50, 1000, 3000)
return <div class="flex flex-col text-4xl text-gray-100 font-bold w-[340px]">
<LerpNum class="rounded-xl bg-slate-600 p-4 mb-4 text-center" value={num1} />
<LerpNum class="rounded-xl bg-slate-600 p-4 text-center" value={num2} decimals={2} />
</div>
}
Formatting, Decimals & Duration
You can fine-tune the interpolation with duration
, decimals
, a custom format()
callback, and even your own easing function.
import { h } from "preact"
import { LerpNum } from "@/comps/varia/lerpnum"
import { useRandomBetween } from "@/comps/varia/utils"
export function LerpNumMoneyDemo() {
const amount = useRandomBetween(5, 500, 1000, 3000)
return <div class="flex flex-col text-4xl text-gray-100 font-bold w-[340px]">
<LerpNum
class="rounded-xl bg-slate-600 p-4 text-center"
value={amount} duration={800}
easing={t => 1 - (1 - t) * (1 - t)}
format={formatUSD}
/>
</div>
}
function formatUSD(n: number) {
const sign = n < 0 ? "-" : ""
const abs = Math.abs(n)
const int = Math.trunc(abs).toString()
const frac = abs.toFixed(2).slice(-2) // always 2 decimals
const withCommas = int.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
return `${sign}$${withCommas}.${frac}`
}
Pausing & Resuming
Set paused
to temporarily stop the interpolation—ideal for game pause menus or performance-sensitive moments:
import { h } from "preact"
import { useState } from "onejs-preact/hooks"
import { LerpNum } from "@/comps/varia/lerpnum"
import { useRandomBetween } from "@/comps/varia/utils"
export function LerpNumPauseDemo() {
const [pause, setPause] = useState(false)
const amount = useRandomBetween(5, 500, 1000, 3000)
function togglePause() {
setPause(!pause)
}
return <div class="flex flex-col text-4xl text-gray-100 font-bold w-[340px]">
<LerpNum
class="rounded-xl bg-slate-600 p-4 text-center"
value={amount}
format={formatUSD}
paused={pause}
/>
<button class="mt-4 border-0 hover:bg-gray-400" onClick={togglePause}>{`${pause ? "Resume" : "Pause"}`}</button>
</div>
}
const formatUSD = (n: number) => `${n < 0 ? "-" : ""}$${Math.trunc(Math.abs(n)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}.${Math.abs(n).toFixed(2).slice(-2)}`
When paused
switches back to false
, the animation continues from the current displayed value toward the latest value
prop.