I'm trying to make a masked TextInput for BRL currency using regex, so every time the user types a number it is formated as follow:
First the number pressed appears inside the TextInput and then you can change the state
to your desired value. Isn't there a way to change the text before it is displayed for the user?
Basically what I'm doing is:
const MoneyTextInput = ({onChangeText, ok}) => {
let [text, setText] = useState('00,00');
return (
<TextInput
value={text}
keyboardType="number-pad"
style={{
width: '100%',
height: '100%',
fontSize: 22,
}}
onChange={({nativeEvent}) => {
setText(prettifyCurrency(nativeEvent.text));
onChangeText(prettifyCurrency(nativeEvent.text));
}}
/>
);
};
And the function with the regex is this:
function prettifyCurrency(value: String): String {
if (!value) {
return '00,00';
}
let newText = value.replace(/(\D)/g, '').replace(/^0+/, '');
if (newText.length < 4) {
for (let i = newText.length; i < 4; i++) {
newText = '0' + newText;
}
}
newText = newText
.replace(/(\d{2}$)/g, ',$&')
.replace(/(\d{1})(\d{3})([,])/, '$1.$2$3')
.replace(/(\d{1})(\d{3})([.])/, '$1.$2$3')
.replace(/(\d{1})(\d{3})([.])/, '$1.$2$3');
return newText;
}
Shouldn't it wait for the value
prop to be updated? Is there anyway I achieve what I want? Because I know in Android (Java) I had a function to change the text before it was displayed.
PS.: I'm using OnChange
function because I found it was a little bit faster than onChangeText