net - UK (2020-01)

(Antfer) #1

Formik


To p Each field requires an
initial value. Otherwise it’s
initialised as undefined,
which React sees as an
uncontrolled component
Above Validation can
also happen on the server.
The function can return a
Promise object that calls a
server and returns errors as
a rejection

pair represents a field and an error message. If a
field has no value in this object, it is deemed to be
valid. The form will only submit when this function
returns an empty object. The function receives the
form values as an argument. For a required field, we
only need to check the value is not an empty string.
Back inside VoteContainer.js, create a validate
callback function to check this value and hook it
up to Formik.


const validate = values => {
const errors = {};
if (values.name === “”) {
errors.name = “Name is required”;
}
return errors;
};
return <Formik [...] validate={validate} />;


These errors are then passed to Vote.js as an errors
prop. To display errors inline, we need to match up
the errors to the particular form field.


function Vote({ isSubmitting, errors, touched }) {[...]}




className={classNames({
“validation-group”: true,
error: !!errors.name && touched.name
})}
>
type=”text” />
{!!errors.name && touched.name && (
{errors.name}

)}


Formik will validate the form every time it updates.
A form with lots of fields would immediately be
swamped with errors after the first change. To avoid
this, we only display the error when a field has
been ‘touched’, meaning it has been interacted with
at some point. When a form submits, Formik will
touch all fields and show any hidden errors.
With the name field complete, we can move to the
answers. The approach we’ve used so far works well
for regular text inputs but is not suited to multiple
inputs that fall under the same field name, such as
a group of radio buttons.
While we can include multiple components
with the same name, we should avoid repeating
ourselves as much as possible. Instead, Formik lets


us pass a custom component into <Field> that can
manage them as one.
The <AnswerGroup> component works similar to
the text input. It takes an options prop, which is an
array containing the options to display. These are
transformed into styled radio buttons that let users
choose an answer. Include this component within
Vote.js. By using <Field> it gets passed the same props
as the name input as well as any extras, in this case
the OPTIONS constant.

import AnswerGroup from “./AnswerGroup”;
<Field component={AnswerGroup} options={OPTIONS}
name=”answer” />

Finally, we need to require an answer in our
validation function in VoteContainer.js as well. The
process there is the same as with the name field.

if (values.answer === “”) {
errors.answer = “Answer is required”;
}

By keeping the validation and submission logic
separate and using Formik to stitch everything
together, we are able to keep each piece small and
easy to understand.^
Free download pdf