reactjstypescriptreact-hook-formshadcnui

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


Solution

  • 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>
      );
    }