I have a Higher Order React component (HOC) which I'm trying to use inside another functional component, wrapping its children:
// HOC
const withSuperpower = <P extends object>(Component: React.ComponentType<P>) => {
// do some stuff...
return (hocProps: P) => {
return (
<>
<div id="superpower" />
<Component {...hocProps} />
</>
);
};
};
// functional component
const = Buddy: React.FC<{children: JSX.Element}>= ({children}) => {
// do some stuff...
return (
<div id="buddy">
{ withSuperpower(<>children</>) } {/* this doesn't compile */}
</div>
);
};
The previous code doesn't compile. It seems that only the later works, when I'm wrapping the component's function/class reference:
export const superBuddy = withSuperpower(Buddy); {/* only this works */}
So to make the first piece of code work I have to create 3rd component which seems to me unnecessary redundant:
const HOCUser:React.FC<{children: React.ReactNode}> = ({children}) => {
return <>{children}</>;
}
const Buddy: React.FC<{children: JSX.Element}> = ({children}) => {
return (
<div id="buddy">
{ withSuperpower(HOCUser) } {/* this works fine */}
</div>
);
}
Is there a better way to use HOC inside functional component's JSX tags block?