Display Error Messages When Necessary

Learn how to display error messages to the user only after they have visited a field.

We were able to display the error messages for each field by getting the message from the formik.errors object in real time. For example, for the “Phone” field, we display the error message using the following snippet:

{
  formik.errors.phone && 
    <small>{formik.errors.phone}</small>
}

Here, we use the short circuit operator && to display the error message only when it exists.

For those wondering why we check that it exists before displaying it (after all, if it doesn’t exist, it displays nothing), the reason why we add the condition is to prevent the entire element (in this case, the <small> tag) from displaying. This is because, sometimes, we could style the element to have padding and border lines, and so, if the node is displayed when there is no error message, we’ll always see the padding and border lines, even when there is no message.

Get hands-on with 1200+ tech skills courses.