Created
July 29, 2022 13:12
-
-
Save alexanderson1993/f884c4dfaf7892d211a779cb48b0b3d9 to your computer and use it in GitHub Desktop.
A currency input field built with Chakra-UI
This file contains hidden or 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
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