Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to properly check if an Array element was touched? #2073

Open
filipetoyoshima opened this issue Nov 27, 2019 · 1 comment
Open

How to properly check if an Array element was touched? #2073

filipetoyoshima opened this issue Nov 27, 2019 · 1 comment
Labels

Comments

@filipetoyoshima
Copy link

❓Question

To render an error message, it is good to check if the field was touched. For example, using bootstrap classes, we do something like:

<div className='form-group'>
    <label htmlFor='email'>E-mail</label>
    <Field
        name='email'
        placeholder='maria.silva@email.com'
        className={`form-control ${
            touched.email && errors.email ? "is-invalid" : "" // Here's my check! <==
        }`}
    />
    <ErrorMessage
        component='div'
        name='email'
        className='invalid-feedback'
    />
</div>

And this works well in most cases, touched.email is yet undefined and JS is able to understand undefined as false. But it gets tricky when dealing with FieldArray.

The problem is when checking something like touched.email[index], well, undefined has no 'index' property. And it gets trickier when we have an array of objects, like touched.friends[index].name

I did some workarounds with try and catch blocks, but I believe that it is not the best option. Does the Formik have some proper way to deal with this?

And, a possible suggestion, isn't it a good idea to send false values when calling touched?

@stale stale bot added the stale label Jan 26, 2020
@arvinsim
Copy link

I also have the same problem with an array of objects touched.lineItems[index].units, touched.lineItems[index].price

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants