Skip to content

Instantly share code, notes, and snippets.

@Taynan-Vieira
Last active November 26, 2021 23:30
Show Gist options
  • Save Taynan-Vieira/fa50b0d417b75a6e7475fcabd984be8f to your computer and use it in GitHub Desktop.
Save Taynan-Vieira/fa50b0d417b75a6e7475fcabd984be8f to your computer and use it in GitHub Desktop.
Text Currency Format
import React from 'react';
import NumberFormat, { FormatInputValueFunction } from 'react-number-format';
interface NumberFormatCustomProps {
inputRef: (instance: NumberFormat | null) => void;
onChange: (event: { target: { value: string } }) => void;
}
const currencyFormatter: FormatInputValueFunction = (value: string) => {
if (!Number(value)) return '';
const amount = new Intl.NumberFormat('pt-BR', {
style: 'decimal',
currency: 'BRL',
minimumFractionDigits: 2,
}).format(Number(value) / 100);
return `${amount}`;
};
function NumberFormatCustom(
props: NumberFormatCustomProps,
): React.ReactElement {
const { inputRef, onChange, ...other } = props;
return (
<NumberFormat
{...other}
NumberFormatCustom
getInputRef={inputRef}
onValueChange={values => {
onChange({
target: {
value: values.value,
},
});
}}
thousandSeparator="."
decimalSeparator=","
format={currencyFormatter}
/>
);
}
export default NumberFormatCustom;
<TextField
id="formatted-numberformat-input"
InputProps={{
inputComponent: NumberFormatCustom as any,
startAdornment: (
<InputAdornment position="start">R$</InputAdornment>
),
}}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment