Skip to content

Instantly share code, notes, and snippets.

@benjaminreid
Created September 15, 2020 16:23
Show Gist options
  • Save benjaminreid/f93f4f1b64230f623a11ced4e64dde59 to your computer and use it in GitHub Desktop.
Save benjaminreid/f93f4f1b64230f623a11ced4e64dde59 to your computer and use it in GitHub Desktop.
import React from 'react';
import {Control, Controller} from 'react-hook-form';
import {TextInputProps} from 'react-native';
import styled from 'styled-components/native';
type InputType = 'text' | 'password' | 'email';
interface InputProps extends TextInputProps {
type?: InputType;
}
function Input({type = 'text', ...rest}: InputProps) {
const textInputProps: {[key in InputType]: Partial<TextInputProps>} = {
text: {},
password: {
autoCompleteType: 'password',
secureTextEntry: true,
},
email: {
autoCapitalize: 'none',
autoCompleteType: 'email',
keyboardType: 'email-address',
},
};
return <StyledTextInput {...rest} {...textInputProps[type]} />;
}
interface ControlledInputProps extends InputProps {
control: Control<Record<string, any>>;
name: string;
defaultValue?: any;
}
export function ControlledInput({
control,
name,
defaultValue = '',
...rest
}: ControlledInputProps) {
return (
<Controller
control={control}
name={name}
defaultValue=""
render={({onChange, onBlur, value}) => (
<Input
onBlur={onBlur}
onChangeText={(value) => onChange(value)}
value={value}
{...rest}
/>
)}
/>
);
}
const StyledTextInput = styled.TextInput`
height: 44px;
background-color: ${(props) => props.theme.colors.input.background};
border-radius: ${(props) => props.theme.border.radius.m}px;
border-color: ${(props) => props.theme.colors.input.border};
border-width: 1px;
padding: 0 ${(props) => props.theme.spacing.m}px;
font: ${(props) => props.theme.font.input};
`;
export default Input;
import {ControlledInput as Input} from '../../Components/Input';
function Form() {
const {control} = useForm<FormData>({
resolver: yupResolver(...schema),
});
return (
<Input control={control} name="day" />
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment