Forms with Formik & Yup - peophins-plasmas/pawsome-app GitHub Wiki
Formik Documentation (includes Yup): https://formik.org/
Formik is a small library that works well with React and React Native that tackles three common issues with forms: 1 .Getting values in and out of form state 2. Validation and error messages 3. Handling form submission
It is also works well with firestore, to use data you need.
Installations: npm i formik npm i yup
The tag takes in a few key parameters: <Formik initialValues={} validationSchema={} onSubmit={(values, actions) => {}} {(props) => ()}
initialValues takes the titles of the fields you want your form to have. For example, {name: '', age: 0}.
validationSchema takes in a function that validates your form (see below)
onSubmit takes in values and actions --> values are set by the initialValues; actions allow for form resetting after submission (actions.resetForm()) onSubmit can take a firestore collection and add to it: ref.add({ name: values.name, age: values.age })
props allows you to use your data to render the form: use from react-native to render each field
i.e. <TextInput style={} placeholder="name" onChangeText={props.handleChange("name")} value={props.values.name />
submitting forms:
handleChange and handleSubmit are both formik properties, so no need to write your own!
- Write a function to pass into validationSchema in
- Can include error messages, passed in as strings
i.e. const FormValidation = Yup.object().shape({ name: Yup.string() .min(2, "too short!") .max(20, "too long!" .required("Required") })
Now you add this function to Formik: schemaValidation={FormValidation} To display error messages, you need to use errors and touched, which should be part of props.
i.e. Underneath your you can include: {props.errors.name && props.touched.name && {props.errors.name}}
This should display your error messages when you try to submit the form.
For more information, please refer to the docs above!