Skip to content

Commit 4cdce1a

Browse files
committed
add HOC
1 parent 24cf34e commit 4cdce1a

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

README.md

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,44 @@ This approach can become repetitive, so we advise creating a simple higher-order
7171
```jsx
7272
// Higher-Order Component to enhance form inputs
7373
import React, { useCallback } from 'react';
74-
// ... [HOC Code] ...
74+
75+
export interface IWithFormInputProps {
76+
form: UseFormReturn<any>;
77+
name: string;
78+
}
79+
80+
export interface IInjectedFormProps {
81+
value: string;
82+
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
83+
onBlur: () => void;
84+
error?: string;
85+
}
86+
87+
function withAJVInput<T>(
88+
WrappedComponent: React.ComponentType<IInjectedFormProps & T>,
89+
) {
90+
return function HOC({ form, name, ...rest }: IWithFormInputProps & T) {
91+
const handleChange = useCallback(
92+
(e: React.ChangeEvent<HTMLInputElement>) => {
93+
form.set({ [name]: e.target.value });
94+
},
95+
[form, name],
96+
);
97+
98+
const handleBlur = useCallback(() => {
99+
form.onBlur(name);
100+
}, [form, name]);
101+
102+
const injectedProps: IInjectedFormProps = {
103+
value: form.state[name]?.value || '',
104+
onChange: handleChange,
105+
onBlur: handleBlur,
106+
error: form.state[name]?.error,
107+
};
108+
109+
return <WrappedComponent {...injectedProps} {...(rest as T)} />;
110+
};
111+
}
75112

76113
const Input = withAJVInput(YourOwnInputComponent);
77114
<Input form={form} name="title" />;

0 commit comments

Comments
 (0)