Reputation: 15627
I refer to this example of creating a React Higher Order Component, taken from this article.
I am struggling to fully comprehend & make use of this HOC.
interface PopupOnHoverPropType {
hoverDisplay: string;
}
const WithPopupOnHover = <P extends object>(BaseComponent: React.FC<P>): React.FC<P & PopupOnHoverPropType> => ({ hoverDisplay, ...props }: PopupOnHoverPropType) => {
const [displayMsg, setDisplayMsg] = useState<boolean>(false);
const toggleDisplayMsg = () => {
setDisplayMsg(displayMsg);
};
return (
<div onMouseEnter={() => setDisplayMsg(true)}>
<div className={`${hoverDisplay} popup`} onClick={toggleDisplayMsg}/>
<BaseComponent {...props as P} />
</div>
)
};
Here is what my understanding of the above code is:
We define a HOC by the name of WithPopupOnHover
,
which takes a React component (BaseComponent).
The BaseComponent comes with its props (referred as P)
which returns a new React component,
which takes props P & the props within PopupOnHoverPropType
.
How do I use this HOC ? The following attempt gives a typescript error that too many arguments are passed in:
const enhanced = WithPopupOnHover(Modal);
const m = Enhanced(a,b,c, "up");
The Modal React component has the following props structure:
const Modal: React.FC<{
a: string;
b(): void;
c(locationData: customType): void;
}> = { ... }
Upvotes: 0
Views: 957
Reputation: 202751
Looks like you just forgot the object brackets. React components all take a single props object argument.
const Enhanced = WithPopupOnHover(Modal);
const m = Enhanced({ a, b, c });
Upvotes: 1