I have a React HOC in TypeScript, but it doesn't seem to work when I call it from within a TSX Component
render
export class HelloWorldComponent extends React.Component<{}, {}> {
public render(): JSX.Element {
return <div>Hello, world!</div>;
}
}
export const withRedText = (Component) => {
return class WithRedComponent extends React.Component<{}, {}> {
public render(): JSX.Element {
return (
<div style={{color: "red"}}>
<Component {...this.props} />
</div>
);
}
};
};
export const HelloWorldComponentWithRedText = withRedText(HelloWorldComponent);
public render(): JSX.Element {
return (
<div>
Test #1: <HelloWorldComponent/>
Test #2: <HelloWorldComponentWithRedText />
Test #3: { withRedText(<HelloWorldComponent />) }
</div>
)
}
HelloWorldComponent
Component = Object {$$typeof: Symbol(react.element), ...}
{ withRedText(<HelloWorldComponent />) }
I don't think that you can invoke a HOC directly / implicitly from JSX. Thinking about the implementation of JSX and how HOCs work, I don't think it would be good for performance: every time the component re-renders, it calls the HOC function again, re-creates the wrapped component class, then invokes it.
You can often get a similar effect, though, by creating a component that takes another component as a parameter:
const WithRedText = ({component: Component, children, ...props}) => (
<div style={{color: "red"}}>
<Component {...props}>{children}</Component>
</div>
);
(I'm passing component
as lowercase, because that seems to be the convention for props, but within WithRedText
, I uppercase it, because that's how JSX identifies custom components as opposed to HTML tags.)
Then, to use it:
ReactDOM.render(
<div className="container">
<WithRedText component={HelloWorldComponent} />
</div>,
);