Skip to content

Instantly share code, notes, and snippets.

@caiomoura1994
Created May 15, 2023 15:10
Show Gist options
  • Save caiomoura1994/6a79cafdebfda28876cdab6b779efa08 to your computer and use it in GitHub Desktop.
Save caiomoura1994/6a79cafdebfda28876cdab6b779efa08 to your computer and use it in GitHub Desktop.
Controlled Input
import { memo } from 'react';
import { StyleSheet, TextInput, TextInputProps } from 'react-native';
import { View } from 'react-native-animatable';
import { useController, useFormContext, UseFormStateReturn, FieldValues, Control, Controller } from 'react-hook-form';
import { CustomLabel } from './CustomLabel';
interface IInput extends TextInputProps {
label: string;
name: string;
referenceValue?: any;
}
interface IInputWithMemo extends IInput {
formState?: UseFormStateReturn<FieldValues>
control?: Control
}
const MemoInput = memo(({ control, name, referenceValue, ...props }: IInputWithMemo) => {
return <>
<Controller
name={name}
control={control}
render={({ field }) => (
<TextInput
style={styles.textInput}
{...props}
{...field}
onChangeText={field.onChange}
ref={(e) => {
field.ref(e)
if (referenceValue) {
referenceValue.current = e // you can still assign to ref
}
}}
/>
)}
/>
</>
}, (prevProps, nextProps) => {
return (
prevProps.formState?.isDirty === nextProps.formState?.isDirty &&
prevProps.editable === nextProps.editable &&
prevProps.name === nextProps.name
);
})
export const ControlledInput = (props: IInput) => {
const { control } = useFormContext();
const { formState } = useController({ name: props.name, control });
return <View style={styles.container}>
<CustomLabel text={props.label} />
<MemoInput formState={formState} control={control} {...props} />
</View>
}
const styles = StyleSheet.create({
textInput: {
height: 40,
borderColor: '#000000',
borderBottomWidth: 1,
marginBottom: 36,
},
container: {
width: '100%',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment