fix(input): sync ref value to internal value (#3533)

* fix: sync ref value to internal value #3024 #3436

* feat: changeset - added changeset

* chore: remove comment

* chore(changeset): add issue numbers

* refactor(input): revise typing

---------

Co-authored-by: Anthony Ortiz <anthonypaulo@hotmail.com>
Co-authored-by: WK Wong <wingkwong.code@gmail.com>
This commit is contained in:
AnthonyPaulO 2024-08-28 22:24:45 -04:00 committed by GitHub
parent 2a34880644
commit a254abf535
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 61 additions and 2 deletions

View File

@ -0,0 +1,5 @@
---
"@nextui-org/input": patch
---
syncs changes to ref value to internal (state) value (#3024, #3436)

View File

@ -126,6 +126,26 @@ describe("Input", () => {
expect(ref.current?.value)?.toBe(value);
});
it("setting ref should sync the internal value", () => {
const ref = React.createRef<HTMLInputElement>();
const {container} = render(<Input ref={ref} type="text" />);
if (!ref.current) {
throw new Error("ref is null");
}
ref.current!.value = "value";
const input = container.querySelector("input")!;
input.focus();
const internalValue = input.value;
expect(ref.current?.value)?.toBe(internalValue);
});
it("should clear the value and onClear is triggered", async () => {
const onClear = jest.fn();

View File

@ -15,7 +15,7 @@ import {useDOMRef, filterDOMProps} from "@nextui-org/react-utils";
import {useFocusWithin, useHover, usePress} from "@react-aria/interactions";
import {clsx, dataAttr, isEmpty, objectToDeps, safeAriaLabel, warn} from "@nextui-org/shared-utils";
import {useControlledState} from "@react-stately/utils";
import {useMemo, Ref, useCallback, useState} from "react";
import {useMemo, Ref, useCallback, useState, useImperativeHandle, useRef} from "react";
import {chain, mergeProps} from "@react-aria/utils";
import {useTextField} from "@react-aria/textfield";
@ -131,7 +131,41 @@ export function useInput<T extends HTMLInputElement | HTMLTextAreaElement = HTML
const disableAnimation =
originalProps.disableAnimation ?? globalContext?.disableAnimation ?? false;
const domRef = useDOMRef<T>(ref);
const domRef = useRef<T>(null);
let proxy: T | undefined = undefined;
useImperativeHandle(
ref,
() => {
if (proxy === undefined) {
proxy = new Proxy(domRef.current!, {
get(target, prop) {
const value = target[prop];
if (value instanceof Function) {
return value.bind(target);
}
return value;
},
set(target, prop, value) {
target[prop] = value;
if (prop === "value") {
setInputValue(value);
}
return true;
},
});
}
return proxy;
},
[domRef.current],
);
const baseDomRef = useDOMRef<HTMLDivElement>(baseRef);
const inputWrapperRef = useDOMRef<HTMLDivElement>(wrapperRef);
const innerWrapperRef = useDOMRef<HTMLDivElement>(innerWrapperRefProp);