onChange doesn’t work on Custom Input inside Controller Wrapper

I’m working on a React project with TypeScript, using react-hook-form and the form components from shadcn/ui (shadcn/ui form example).
I’ve created a custom Input component with a button (containing a pen icon) that toggles the readonly property of the input.

Desired Functionality

When the user clicks the pen button, the input becomes editable.
As soon as the input value changes, replace the pen button with a submit button.
The input should return to readonly state only after the submit button is clicked and the form is submitted.
This behavior should apply to every input in the form.

Problem

The onChange property doesn’t seem to work for detecting value changes or setting a state to swap the buttons.
Attempting to use react-hook-form hooks like useFormContext to get the control prop, and then using useWatch or useFormState, results in excessive re-renders.

I’m looking for suggestions on how to implement this functionality efficiently. If you have ideas on how to modify my current component to achieve this, I’d greatly appreciate your help.

Implementation on Stackblitz

StackBlitz – Playground

8

Since you have access to formContext you should be able to do something like this.

const EditableInput = React.forwardRef<HTMLInputElement, EditableInputProps>(
({ className, editPermission = true, ...props }, ref) => {

    const {formState, getValues, resetField} = useFormContext(); // returns all the same methods and properties that useForm does. 

    const [canEdit, setCanEdit] = React.useState<boolean>(false);
    const disabled = props.disabled || !editPermission;

    const handleEdit = () => {

        const value = getValue(props.name)
         ....do something with the value....
        if (!disabled) {
            setCanEdit((prev) => !prev);
        }
       ...finally...
       resetField(props.name, {defaultValue:value})  // this should reset the dirty state and the default value for the field so dirty can be properly detected. 
       
    };

    const isDirty = formState.dirtyFields[props.name]  // this should be stateful and usable in your JSX to trigger conditional rendering. 

    return (
        <div className="relative">......


That will allow you to listen to the specific fields dirty state, get the value of the field on demand and then reset the field and it’s default value which should also trigger the field to no longer be dirty.

Note on using the old render props and Controller api

Value and isDirty might be available directly on props, it might be worth investigating.

Small example with a typical form Implementation

Here is a link to a playground showing how this would work with a typical implementation of react-hook-form Stackblitz – Playground

Editable Input component

import {
  ChangeEventHandler,
  forwardRef,
  useEffect,
  useRef,
  useState,
} from 'react';
import { Controller, useFormContext } from 'react-hook-form';

type Props = {
  name: string;
};

type InputProps = {
  name: string;
  onChange: (val: string) => void;
  value: string;
};

const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
  { value, ...props }: InputProps,
  ref
) {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const {
    formState: { dirtyFields },
    resetField,
    getValues,
  } = useFormContext();
  const isDirty = !!dirtyFields[props.name];
  const handleChange: ChangeEventHandler<HTMLInputElement> = (e) => {
    const val = e.target.value;
    props.onChange?.(val);
  };

  const handleUpdate = () => {
    const value = getValues(props.name);
    resetField(props.name, { defaultValue: value });
    setIsEditing(false);
  };

  useEffect(() => {
    if (isEditing) {
      inputRef.current?.focus();
    }
  }, [isEditing]);
  return (
    <div className="input-wrapper">
      <input
        ref={(e) => {
          if (e) {
            inputRef.current = e;
          }
          if (typeof ref === 'function') {
            ref(e);
          }
        }}
        type="text"
        value={value}
        name={props.name}
        onChange={handleChange}
        disabled={!isEditing}
        className={isEditing ? 'active' : ''}
      />
      {isDirty ? (
        <button type="button" onClick={handleUpdate}>
          Update
        </button>
      ) : (
        <button
          type="button"
          onClick={() => {
            setIsEditing((p) => !p);
          }}
        >
          Edit
        </button>
      )}
    </div>
  );
});

export default function EditableInput(props: Props) {
  return (
    <Controller
      name={props.name}
      render={(props) => {
        return (
          <Input
            value={props.field.value}
            name={props.field.name}
            onChange={props.field.onChange}
            ref={props.field.ref}
          />
        );
      }}
    />
  );
}

form component

import { useState } from 'react';
import EditableInput from './enditable-input';
import { useForm, FormProvider, SubmitHandler } from 'react-hook-form';

const defaultValues = {
  field1: '',
  field2: '',
  field3: '',
  field4: '',
};

export default function Form() {
  const [result, setResult] = useState<typeof defaultValues | null>(null);
  const methods = useForm({ defaultValues });
  const handleSubmit: SubmitHandler<typeof defaultValues> = (data) => {
    setResult(data);
  };
  const handleReset = () => {
    setResult(null);
    methods.reset(defaultValues);
  };
  return (
    <div className="form-container">
      <FormProvider {...methods}>
        <form
          className="form"
          id="form-test"
          onSubmit={methods.handleSubmit(handleSubmit)}
        >
          <EditableInput name="field1" />
          <EditableInput name="field2" />
          <EditableInput name="field3" />
          <EditableInput name="field4" />
        </form>
        <div className="control-container">
          <button type="submit" form="form-test" className="button">
            Submit
          </button>
          <button
            type="button"
            className="button"
            onClick={() => handleReset()}
          >
            reset
          </button>
        </div>
      </FormProvider>
      {result && <pre>{JSON.stringify(result, null, 2)}</pre>}
    </div>
  );
}

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật