Last active
April 23, 2018 23:44
-
-
Save sibelius/bd2fcb5b64168150d7b24000268fd6d9 to your computer and use it in GitHub Desktop.
Formik TextInput example
This file contains 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
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); |
This file contains 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 * 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