Skip to content

Instantly share code, notes, and snippets.

@sibelius
Last active April 23, 2018 23:44
Show Gist options
  • Save sibelius/bd2fcb5b64168150d7b24000268fd6d9 to your computer and use it in GitHub Desktop.
Save sibelius/bd2fcb5b64168150d7b24000268fd6d9 to your computer and use it in GitHub Desktop.
Formik TextInput example
class ExampleForm extends React.Component<Props> {
render() {
return (
<View>
<TextInput name={'email'} />
</View>
);
}
}
export default withFormik({
validationSchema: yup.object().shape({
email: yup.string().required('email is required'),
}),
handleSubmit: () => {
//console.log('handleSubmit: ', values, props);
},
})(ExampleForm);
import * as React from 'react';
import PropTypes from 'prop-types';
import type { FormikContext } from 'formik';
type Props = {
name: string,
} & FormikContext;
export default class FormikReactNativeTextInput extends React.Component<Props> {
static contextTypes = {
formik: PropTypes.object,
};
handleChange = value => {
this.context.formik.setFieldValue(this.props.name, value);
};
handleBlur = () => {
this.context.formik.setFieldTouched(this.props.name, true);
};
render() {
// we want to pass through all the props except for onChangeText
const { onChangeText, ...otherProps } = this.props;
const { name } = this.props;
const { formik } = this.context;
const wasTouched = formik.dirty ? formik.touched[name] : false;
const fieldError = wasTouched && formik.errors[name];
return (
<TextInput
value={formik.values[name]}
onChangeText={this.handleChange}
onBlur={this.handleBlur}
{...otherProps}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment