Last active
November 26, 2021 23:30
-
-
Save Taynan-Vieira/fa50b0d417b75a6e7475fcabd984be8f to your computer and use it in GitHub Desktop.
Text Currency Format
This file contains 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
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; |
This file contains 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
<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