2023-01-23

React hook form pass an array of values to child - some Regster and some not

I want to pass an array of strings to my Child Component which creates an input field managed by React Hook Form.

Sometimes, I want the React Hook Form to NOT register some fields in the array passed as the input fields are optional to the user. For example, address_line2 in the inputForm array is not always required to be completed on the form.

I use this Child Component in a number of places, so if I change it, is it possible to make the change or component optional or use an if statement? So, that i can continue to use the child component as is.

Here is the parent component:

const StopForm: React.FC<IProps> = ({ id, index, stop }) => {
  const Router = useRouter();

  const {
    register,
    handleSubmit,
    unregister,
    formState: { errors },
  } = useForm<Stop>({
    defaultValues: sampleStopData,
  });

  const inputFields = [
    "address_line1",
    "address_line2",
  ];
return (
<>
  {inputFields.map((field, index) => (
          <InputField
            key={index}
            val={field}
            register={register}
            defaultValue={
              typeof stop === "object" &&
              typeof stop[field as keyof Stop] !== "undefined"
                ? // ? stop[field as keyof Stop].toString()
                  String(stop[field as keyof Stop])
                : ""
            }
            errors={errors}
            classes="px-3 py-1.5 rounded placeholder:text-gray-800 lg:w-[25rem] lg:mx-auto bg-transparent border outline-none"
          />
        ))}
</>);

My Child Component that manages the react hook form part is this:

interface IProps {
  val: string;
  type?: string;
  defaultValue: string;
  register: UseFormRegister<any>;
  errors: any;
  classes: string;
}

const InputField: React.FC<IProps> = ({
  defaultValue,
  register,
  errors,
  val,
  classes,
  type = "text",
}) => {
  return (
    <>
      <input
        id={val}
        type={type}
        placeholder={val}
        className={`${classes} ${
          errors?.val ? "border-red-900" : "border-gray-400"
        }`}
        defaultValue={defaultValue}
        {...register(val, {
          required: { value: true, message: `${val} is required` },
        })}
      />
      {errors[val] && (
        <small className="text-red-700">{errors[val].message}</small>
      )}
    </>
  );
};

export default InputField;

Can the input fields also pass a value or somehow let the child component know to 'skip' that value and not register it?

Any assistance on how to do this - I have been going round and round on this one, wouuld be graciously received!

Thank you! Karen



No comments:

Post a Comment