I have created my own Texfield which I use throughout my app. I would now like to create a Textfield which has a predefined format of the input. So for example as seen below in the image I want the text to always have the format dd/mm/yyyy
and that the input jumps to the month when the date is filled in.
This image is an example of what I try to accomplish:
This is my custom Textfield which is basically the native TextInput
with some styling.
//Input.tsx
interface Props {
errorMessage?: string
placeholder: string
value: string
onChange: (text: string) => void
}
const Input: React.FC<Props> = ({
errorMessage,
placeholder,
onChange,
value,
}) => {
const [focused, setFocused] = useState(false)
return (
<Box marginVertical="xs">
<Box
borderColor={errorMessage ? 'error' : focused ? 'primary' : 'inputBG'}
paddingVertical="inputS"
paddingHorizontal="inputM"
borderRadius="s"
borderWidth={2}
backgroundColor={errorMessage ? 'inputErrorBG' : 'inputBG'}
>
<TextInput
placeholder={placeholder}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onChangeText={onChange}
value={value}
/>
</Box>
{errorMessage ? <Text color="error">{errorMessage}</Text> : null}
</Box>
)
}
I found this package which provides the component MaskInput
which makes it possible to define masks to format the input.
Below I extended my custom Input
with the variant
props to display the MaskInput when the variant is "date".
import MaskInput, { Masks } from 'react-native-mask-input'
{variant === 'date' ? (
// @ts-ignore
<MaskInput
placeholder="dd/mm/yyyy"
mask={Masks.DATE_DDMMYYYY}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onChangeText={(formatted) => onChange(formatted)}
value={value}
keyboardType={keyboardType}
/>
) : (
<TextInput
placeholder={placeholder}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onChangeText={onChange}
value={value}
keyboardType={keyboardType}
/>
)}