Skip to content

Instantly share code, notes, and snippets.

@alexanderson1993
Created July 29, 2022 13:12
Show Gist options
  • Save alexanderson1993/f884c4dfaf7892d211a779cb48b0b3d9 to your computer and use it in GitHub Desktop.
Save alexanderson1993/f884c4dfaf7892d211a779cb48b0b3d9 to your computer and use it in GitHub Desktop.
A currency input field built with Chakra-UI
function CurrencyInput({
value,
onChange,
max,
}: {
value: number;
max: number;
onChange: (val: number) => void;
}) {
const [error, setError] = useState('');
return (
<>
<Input
inputMode="numeric"
pattern="[0-9,$.]*"
defaultValue={formatCurrency.format(value / 100)}
onChange={(e) => {
const preParse = e.target.value.replace(/[$,]/g, '');
const num = Number(preParse) * 100;
if (isNaN(num)) {
setError('Invalid down payment input.');
return;
}
if (num > max) {
setError(`Amount must be less than or equal to ${formatCurrency.format(max / 100)}.`);
return;
}
setError('');
onChange(num);
}}
/>
{error && (
<Text fontSize="sm" color="red.500">
{error}
</Text>
)}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment