React hook form share ref with useFormContext()

39 views Asked by At

i'am currently using a useFormContext from React-hook-form because i've got plenty of nested components in which i have my inputs.

I managed to register my fields, but i'm struggling with a ref.

I'd like to use a useRef to auto resize my textArea, but as soon as I add the ref={} to my textarea, i'm loosing the link with reactHookForm. I've seen that I could share the ref, but i don't succeed to apply it in my case. Thanks

const SectionGeneralInfos = () => {
      const dispatch = useDispatch();
      const toy = useSelector(selectSortingToy);

      const descriptionRef = useRef<HTMLTextAreaElement>(null);

      useEffect(() => {
        if (descriptionRef.current) {
          const height = descriptionRef.current.scrollHeight;
          descriptionRef.current.style.height = `${height}px`;
        }
      }, [descriptionRef.current && descriptionRef.current!.scrollHeight]);


      return (
        <section>
          <h3>Informations générales</h3>
          <ConnectToyForm>
            {({ register, formState: { errors } }) => (          
                <div className="description_field">
                  <label
                    className="block mb-2 font-light text-sm text-yoti_blue50"
                    htmlFor="description"
                  >
                    Description
                  </label>
                  <textarea
                    {...register("description", {
                      onChange(e) {
                        dispatch(
                          changeTextInputValue({
                            fieldName: e.target.name,
                            value: e.target.value,
                          })
                        );
                      },
                    })}
                    defaultValue={toy?.description || ""}
                    rows={1}
                    placeholder="Entrez votre description ici"
                    id="description"
                  />
                  {errors.description && (
                    <p className="mt-2 text-sm text-yoti_red">
                      {errors.description.message}
                    </p>
                  )}
                </div>
              </>
            )}
          </ConnectToyForm>
     </section>
      );
    };

0

There are 0 answers