James Swanson
James Swanson

Reputation: 61

How to style Formik fields based on error and touched state

I have a question about rendering errors when using [email protected] to create forms in React.

I am trying to figure out how to properly render different styles for my input based on whether or not the input has been touched and has errors.

 {({ values, error, touched }) => (
        <Form>
          <Field name="Lawn" type="text">
            {({ field, form }) => (
              <Input
                style={form.touched.Lawn && form.errors.Lawn ? 
                                   { style } : { styleError }}
                {...field}
                type="text"
                placeholder="Lawn Details"
              />
            )}
          </Field>

const style = {
  margin: '1em 0em',
  fontSize: '1.5em',
  backgroundColor: 'white',
};

const styleError = {
  margin: '1em 10em',
  fontSize: '1.5em',
};

I believe my error has to do with not properly accessing the touched and error states in the form.

Any help would be very appreciated.

Upvotes: 3

Views: 10481

Answers (1)

Ciar&#225;n Tobin
Ciar&#225;n Tobin

Reputation: 7526

You're close, you just incorrectly passed style and styleError. They should not be surrounded with braces (and they're also backwards because the error formatting will show when there is no error and vice versa).

<Input
    style={form.touched.Lawn && form.errors.Lawn ? styleError : style}
    {...field}
    type="text"
    placeholder="Lawn Details"
/>

Here's a full example.

Upvotes: 2

Related Questions