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
})}
>
{!!errors.name && touched.name && (
)}