react-hook-form: How to reference errors when i'm programatically are rendering components

I got a code like this

const ExampleForm= ({ data,}) => { 
const { handleSubmit, register, reset, errors, control} = useForm();
return (

    <form onSubmit={handleSubmit(onSubmit)} className={classes.root}>
       <IterateFormData datos={data} regis={register} err={errors} control={control}/>
 </form>

  );
};

That renders inputs depending of the data that i’m recieving from props. and im using nombreVariable as the input name, but when i’m referencing the name of the input to validate errors i’m not getting anything at all, the register is working.

const IterateFormData = ({ datos, regis, err, control }) => {
 let tamanio = data.length > 4? 3 : data.length === 3? 4 : data.length === 2? 6 : 3
  
  for (let i = 0; i < data.length; i++) {
    let info = [];
    let nombreVariable = `${data[i].nombreAtributo}-${data[i].idAtributo}`;

    if (data[i].predefinido === "t") {
 info.push(
            <Grid item xs={tamanio}>
              <TextField
                variant="outlined"
                error={err.nombreVariable? true : false}
                color="secondary"
                type="date"
                name={nombreVariable}
                label={`${data[i].nombreAtributo}*`}
                inputRef={regis({required: true})}
                helperText={err.nombreVariable && "Campo requerido"}
                InputLabelProps={{
                  shrink: true,
                }}
              />
            </Grid>
          );
}

I’m correctly doing the reference of the errors or there is another way to achieve this?

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 24 (12 by maintainers)

Most upvoted comments

https://codesandbox.io/s/react-hook-form-mui-iterate-json-properties-jm0zi?file=/src/App.js This is a little code example, hope i get into the point c:

Edit: don’t forget to test it outside CSB browser, it may not render the changes in the inputs.

I solve it at the end by handling the errors as an array, so inside my loop where i create my fields i just reference them by errors[inputName], and a MUI native select do the work pretty well.

awesome @Jsramosra please share some code snippet if you can, this will help others.

sounds like you are doing useFieldArray? have you looked at that.