Skip to content

Instantly share code, notes, and snippets.

@leodr
Created March 9, 2021 15:57
Show Gist options
  • Save leodr/f8fee7164e849907e95f5495153b3456 to your computer and use it in GitHub Desktop.
Save leodr/f8fee7164e849907e95f5495153b3456 to your computer and use it in GitHub Desktop.
A React hook for creating mobile-friendly, auto-formatted money inputs.
import { KeyboardEvent, useState } from 'react';
interface MoneyInputReturn {
cents: number;
setCents: (newCents: number) => void;
stringValue: string;
handleKeyUp: (event: KeyboardEvent<HTMLInputElement>) => void;
}
/**
* A React hook to implement a formatted currency input.
*/
export function useMoneyInput({ max = Infinity } = {}): MoneyInputReturn {
const [cents, setCents] = useState(0);
function handleKeyUp(event: KeyboardEvent<HTMLInputElement>) {
if (['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(event.key)) {
const amount = Number(event.key);
setCents((previous) => {
const newAmount = previous * 10 + amount;
if (newAmount < max * 100) {
return newAmount;
}
return previous;
});
} else if (event.key === 'Backspace') {
setCents((previous) => Math.floor(previous / 10));
}
}
const stringValue = (cents / 100).toLocaleString(navigator.languages[0], {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
return {
cents,
setCents,
stringValue,
handleKeyUp,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment