Formik
Formik is designed to let validation happen in a way that
suits each individual project. It has form- and field-level
validation and can be written as plain JavaScript. For a more
structured approach, it also supports Yup – an object schema
validator package.
There are two phases to validation using Yup. The first is
the creation of an object schema. This describes the shape of
a particular object. The package comes with a few standard
descriptors to validate the data for each field. Using yup.email()
for example, would check the value is a valid email address. This is
similar to how React’s prop types work.
const schema = Yup.object().shape({
name: Yup.string().required(“Name is required”),
});
Once a schema is constructed, it can then be used as a parser
for a supplied object. The isValid method on each schema returns a
Promise object that resolves or rejects depending on the validity.
Formik makes use of Yup schemas by consuming a
validationSchema prop. This replaces the manual validate callback
function and additionally handles all of the mapping of values to
fields internally.
<Formik validationSchema={schema} />
The structure of an object schema is designed to be easily
understood by developers not familiar with Yup or how it works.
By using it as a schema for a Formik-based form, it makes the
validation rules clear and tells developers the exact structure they
can expect the data to be returned in.
Learn more about Yup and its extra functionality at https://
github.com/jquense/yup
VALIDATE WITH YUP
Then add it into the application. IN-DEPTH
Formik forms can be created in two ways. The
withFormik higher-order component enables us to
wrap an existing component or use the
component with a render prop that performs the
same function, which is what we will be using.
Inside VoteContainer.js, create a functional
component that will hold all the logic for the form.
This returns a
form. Provide a starting value for the fields we will
add later on through the initialValues prop.
import { Formik } from “formik”;
import Vote from “./Vote”;
function VoteContainer() {
return <Formik
initialValues={{ name: “”, answer: “” }}
render={props => <Vote {...props} />} />
}
The
having the Formik logic separate we can keep the
form component as simple as possible.
Create a Vote component inside Vote.js that makes
use of the
import { Form } from “formik”;
function Vote() {
return (
);
}
Formik keeps track of the changes to each field and
will provide them once the form is submitted. It
does all this through the events emitted from the
form and each field within it.
At a form level there are two specific events –
submit and reset. When a form submits, we need
Formik to take over and perform its checks, with
the reset event clearing the state. The imported