Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

formik

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?

like image 443
Josh Winters Avatar asked Dec 14 '22 11:12

Josh Winters


2 Answers

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" />

...
like image 168
ron4ex Avatar answered Jan 09 '23 20:01

ron4ex


When i try the technique suggested in the accepted answer for ErrorMessage component using

<ErrorMessage name="propertyName" style={{ color: 'red'}}/>

it didn't work for me. It worked when i enclosed it inside another container though.

<div style={{ color: 'red'}}>
     <ErrorMessage name="propertyName" />
</div>

Hope this helps someone.

like image 24
James Poulose Avatar answered Jan 09 '23 22:01

James Poulose