Search code examples
cssformik

How do I style the borders of a formik error field?


I know how to style it with regular form inputs/selects/etc, but I have switched from using those to Formik Field, and the above doesn't work the same way.

<Formik
  initialValues={{
    example: ''
  }}
  validate={(values) => {
    const errors = {};

    if (!values.example) errors.example = 'Required';

    return errors;

  }}
  onSubmit={this.handleSubmit}
  render={formProps => {
    return (
      <Form>
        <Field type='text' name='example' />
        <ErrorMessage name='example' />
      </Form>
    )
  }} />

So how would I change the border of the input from whatever it is normally to red if it is empty on submit?


Solution

  • Solution

    You can style Field and ErrorMessage components provided by Formik just like you would style any other component in react. I created a working demo for you here: https://stackblitz.com/edit/react-formik-field-error-styles

    Have a look. Continue reading for explanation.

    Explanation

    The simplest way would be to use style prop:

    function getStyles(errors, fieldName) {
      if (getIn(errors, fieldName)) {
        return {
          border: '1px solid red'
        }
      }
    }
    
    ...
    
    <Field style={getStyles(formProps.errors, 'example')} type='text' name='example' />
    
    ...
    

    However, if you need manageable customizations, I would recommend you create a custom component. Field provides you with a component prop to which you can assign your own custom component like CustomInput or something like so:

    
    function getStyles(errors, fieldName) {
      if (getIn(errors, fieldName)) {
        return {
          border: '1px solid red'
        }
      }
    }
    
    function CustomInput({ field, form: { errors } }) {
    
      return <div>
        <input {...field} style={getStyles(errors, field.name)} />
        <ErrorMessage name={field.name} />
      </div>
    }
    
    ...
    
    <Field component={CustomInput} type="text" name="example" />
    
    ...