React-hook-form: How to check for individual errors on a fieldArray?

Created on 5 Feb 2020  路  1Comment  路  Source: react-hook-form/react-hook-form

I have a fieldArray that I want to show individual errors for each of the fields. Using Material-UI and Typescript. Currently I have to add this rule to my tsconfig...

suppressImplicitAnyIndexErrors": true

to avoid this error.

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'FieldError which specifically pointing to the error checking part... errors.taskChecks[i] && typeof errors.taskChecks[i].name

Here is one of the fields...

<TextField
                            fullWidth
                            label="Name"
                            defaultValue={check.name}
                            name={`taskChecks[${i}].name`}
                            inputRef={register({
                                required: "This field is required",
                                minLength: {value: 3, message: "Must be at least 3 characters"},
                                maxLength: {value: 255, message: "Must be no more than 255 characters"}
                            })}
                            error={!!errors.taskChecks && errors.taskChecks[i] && typeof errors.taskChecks[i].name !== 'undefined'}
                            helperText={!!errors.taskChecks && errors.taskChecks[i] && typeof errors.taskChecks[i].name !== 'undefined' && errors.taskChecks[i].name.message}
                        />

You can see it's quite annoying how far I have to check and then again to show the helperText dynamically.

Is there another way to do this so I don't have to suppress that type error?

Most helpful comment

I ended up with the following which is pretty nice and i dont have to add the type rule.

error={!!errors.taskChecks?.[i].name}
helperText={errors.taskChecks?.[i].name?.message}

and typing the formContext...

const { control, register, errors } = useFormContext<{taskChecks: DisplayedTaskCheck[]}>();

>All comments

I ended up with the following which is pretty nice and i dont have to add the type rule.

error={!!errors.taskChecks?.[i].name}
helperText={errors.taskChecks?.[i].name?.message}

and typing the formContext...

const { control, register, errors } = useFormContext<{taskChecks: DisplayedTaskCheck[]}>();

Was this page helpful?
0 / 5 - 0 ratings