MCPcopy Create free account
hub / github.com/dailydotdev/apps / useInputField

Function useInputField

packages/shared/src/hooks/useInputField.ts:17–66  ·  view source on GitHub ↗
(
  value: string | ReadonlyArray<string> | number,
  valueChanged?: (value: string) => void,
)

Source from the content-addressed store, hash-verified

15}
16
17export function useInputField<T extends ValidInputElement = HTMLInputElement>(
18 value: string | ReadonlyArray<string> | number,
19 valueChanged?: (value: string) => void,
20): UseInputField<T> {
21 const inputRef = useRef<T>(null);
22 const [focused, setFocused] = useState<boolean>(false);
23 const [hasInput, setHasInput] = useState<boolean>(false);
24
25 const setInput = (newValue: string): void => {
26 inputRef.current.value = newValue;
27 inputRef.current.dispatchEvent(new Event('input', { bubbles: true }));
28 };
29
30 useEffect(() => {
31 if (value !== undefined) {
32 setInput(value?.toString() || '');
33 setHasInput(!!inputRef?.current?.value?.length);
34 }
35 }, [value]);
36
37 const onFocus = () => setFocused(true);
38 const onBlur = () => setFocused(false);
39
40 const onInput = (event: SyntheticEvent<T, InputEvent>): void => {
41 if (valueChanged) {
42 valueChanged(event.currentTarget.value);
43 }
44 const len = event.currentTarget.value.length;
45 if (!hasInput && len) {
46 setHasInput(true);
47 } else if (hasInput && !len) {
48 setHasInput(false);
49 }
50 };
51
52 const focusInput = () => {
53 inputRef.current.focus();
54 };
55
56 return {
57 inputRef,
58 focused,
59 hasInput,
60 onFocus,
61 onBlur,
62 onInput,
63 focusInput,
64 setInput,
65 };
66}

Callers 2

SearchField.tsxFile · 0.90
useInputFieldFunctionsFunction · 0.90

Calls 1

setInputFunction · 0.85

Tested by

no test coverage detected