'Issue to handle React-Hook-Form errors object in combination with es6 literal templates

The code below shows a table where I have a series of rows and columns based on the following arrays:

const weekDays = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
  "Sunday",
];

const timeWindows = [
  "openOrder",
  "closeOrder",
  "openPickupOrder",
  "closePickupOrder",
];

Based on the above values, I also dynamically generate the fields names by using es6 literal templates.

The problem starts when I try using the react-form-hook errors object in combination with the dynamically generated names (es6 literal templates). Errors don't work.

     <table>
        <tbody>
          {weekDays.map((day) => (
            <tr key={day}>
              <td>{day}</td>
              <td>
                <ToggleButton label={day} statusRow={statusRow} />
              </td>
              {timeWindows.map((window) => (
                <td key={`${day}${window}`}>
                  <input
                    {...register(`${window}${day}`, {
                      required: true,
                    })}
                    type="time"
                  />
                  {`${errors}.${window}${day}` && ( <---- ISSUE IS HERE
                    <span>This field is required</span>
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>

I'm trying to combine an es6 literal template with an object and have in return the following:

errors.openOrderMonday

If I console.log(${errors}) I get [object Object], and if I try console.log(errors.${window}${day}`), yes it returns the full string (above) but it's NOT read as an object.

Any help is much appreciated.

Thanks Joe



Solution 1:[1]

UPDATE:

I had 2 issues here:

  • I wasn't able to use literal templates with an object to display errors
  • With the solution suggested by other devs, the errors object was returning undefined

Cause of the issue:

  • Issue 1 was caused by the code structure
  • Issue 2 was caused by the fact that in the component AND its parent, I was initializing errors and register. Practically I was doing it twice.

Fix:

  • Issue 1: the initial suggestion by Pranay Nailwal fixed the issue errors[`${window}${day}`]
  • Issue 2: Instead of initializing errors and register twice, I passed those as props from the parent component

I removed this from my child component:

const {
    register,
    formState: { errors },
  } = useForm();

I used this:

const { register, errors } = props;

Thanks everyone for the help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe