Issue
I'm trying to add functionality to input mm/yy fields so as when the users enters 2 digits, slashes "/" get automatically added.
here's my TextInput
<TextInput
placeholder="mm/yy"
placeholderTextColor={Colors.BLACK_TRANSPARENT_50}
keyboardType="number-pad"
maxLength={4}
returnKeyType="done"
style={styles.secondtextinput}
></TextInput>
Solution
I just did something like this in my app for adding a "-" in phone numbers :) It might be a bit of a roundabout fix, but here's what I did:
I used the useState
hook to manage state in my functional component.
const [date, setDate] = useState("");
<TextInput
onChangeText={(text) => {
setDate(
text.length === 3 && !text.includes("/")
? `${text.substring(0, 2)}/${text.substring(2)}`
: text
);
}}
placeholder="mm/yy"
placeholderTextColor={Colors.BLACK_TRANSPARENT_50}
keyboardType="number-pad"
maxLength={5}
returnKeyType="done"
style={styles.secondtextinput}
value={date}
/>
I changed the maxLength
to 5 to account for the "/". As the user inputs the date, once it gets to a length of 3, it checks for any existing "/"s and, if there aren't any, it adds one in after the second character.
Answered By - FredAstaire