How To Change Text Immediately In Onchangetext Callback?
I have a case i want to do 'Write Time' So I have a TextInput user can write a time 'numbers' now as usually i set state with new char using onChangeText So now i want to replace t
Solution 1:
To this fix this problem here is an approach I suggest:
- Make sure we always have 4 digit number in the input
- If the user makes the text input blurred after entering less then 4 digits add leading zeros to make the input as 4 digit
Here is a simple snippet of code to achieve this.
const [inputTime, setTime] = React.useState(null);
return (
<View style={styles.container}>
<TextInput
maxLength={5}
placeholder="07:00"
placeholderTextColor="#707070"
onBlur={(e) => {
let { text } = e.nativeEvent;
let values = text.split(":");
let value = "";
if(values.length==1){
value = values[0].substring(0,4).padStart(4, 0);
value = value.substring(0, 2) + ':' + value.substring(2);
setTime(value);
}elseif(values.length==2){
value = `${values[0].padStart(2, 0)}:${values[1].padEnd(2, 0)}`;
setTime(value);
}
else{
console.log('wrong input')
}
}}
/>
<Text>{`Formatted time is ${inputTime}`}</Text>
</View>
);
Here is the Snack https://snack.expo.io/@saachitech/477b89
Tested with below conditions
Input 123 will be converted to01:23
Input 1234 will be converted to12:34
Input 12121 will be converted to12:12
Input 12:1 will be converted to12:10
Input 1:23 will be converted to01:23
Input 12:23 won't have any effect and remain 12:23
Input 01:23 won't have any effect and remain 01:23
Post a Comment for "How To Change Text Immediately In Onchangetext Callback?"