-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwithStateValue.tsx
More file actions
29 lines (22 loc) · 1.06 KB
/
withStateValue.tsx
File metadata and controls
29 lines (22 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React, { FC, useState } from 'react';
type OnChangeFn<T> = (value: T, ...args: any[]) => any; // eslint-disable-line @typescript-eslint/no-explicit-any
interface WrappedComponentProps<T> {
onChange?: OnChangeFn<T>;
value: T;
[key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default <T,>(WrappedComponent: FC<any>) => {
const WrapperComponent = ({ value, onChange, ...restProps }: WrappedComponentProps<T>) => {
const [componentValue, setComponentValue] = useState(value);
const handleChange = (...args: Parameters<OnChangeFn<T>>): ReturnType<OnChangeFn<T>> => {
setComponentValue(args[0]);
if (onChange) {
onChange(...args);
}
};
return <WrappedComponent {...restProps} onChange={handleChange} value={componentValue} />;
};
WrapperComponent.displayName = `withStateValue(${WrappedComponent.displayName ?? WrappedComponent.name})`;
return WrapperComponent;
};