Last active
January 29, 2026 11:03
-
-
Save intergalacticspacehighway/38daf5a9aff99b1c0384884459dfe0f6 to your computer and use it in GitHub Desktop.
Synchronous validation with React Native TextInput
This file contains hidden or 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 { TextInput } from 'react-native'; | |
| import Animated, { | |
| useAnimatedRef, | |
| useHandler, | |
| dispatchCommand, | |
| useEvent, | |
| } from 'react-native-reanimated'; | |
| const AnimatedTextInput = Animated.createAnimatedComponent(TextInput); | |
| function ReanimatedTextInput() { | |
| const animatedRef = useAnimatedRef(); | |
| const handlers = { | |
| onChange: (event: any) => { | |
| 'worklet'; | |
| console.log('event', event); | |
| }, | |
| }; | |
| const { doDependenciesDiffer } = useHandler(handlers); | |
| const textInputHandler = useEvent( | |
| (event: any) => { | |
| 'worklet'; | |
| const { onChange } = handlers; | |
| if (onChange) { | |
| const textWithoutSpecialCharacters = event.text.replace(/[^a-zA-Z]+/g, ''); | |
| if (textWithoutSpecialCharacters !== event.text) { | |
| dispatchCommand(animatedRef, 'setTextAndSelection', [ | |
| event.eventCount, | |
| textWithoutSpecialCharacters, | |
| -1, | |
| -1, | |
| ]); | |
| } | |
| onChange(event); | |
| } | |
| }, | |
| ['onChange'], | |
| doDependenciesDiffer | |
| ); | |
| return ( | |
| <AnimatedTextInput | |
| style={{ height: 40, borderColor: 'gray', borderWidth: 1, marginTop: 100 }} | |
| onChange={textInputHandler} | |
| ref={animatedRef} | |
| /> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment