Reputation: 808
I am trying to create a decorator which takes an argument from React. Context provider, If I want to create HOC it is easy:
interface DashboardProps {
user: User;
}
class Dashboard extends React.Component<DashboardProps> {
render() {
return (<span>{this.props.user.name}</span>);
}
}
function withUser(WrappedComponent) {
return class extends React.Component {
render() {
return (
<UserContext.Consumer>
{user => <WrappedComponent user={user} {...this.props}>}
</UserContext.Consumer>
);
}
}
}
export default withUser(Dashboard);
But I am not sure how to write it like a decorator:
@withUser
class Dashboard ...
Upvotes: 1
Views: 1398
Reputation: 357
The type of class decorator in typescript looks like this:
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
Which means a class decorator function must return a same typed component, or nothing.
function withUser(WrappedComponent): void {
return class extends React.Component {
render() {
return (
<UserContext.Consumer>
{user => <WrappedComponent user={user} {...this.props}>}
</UserContext.Consumer>
);
}
} as unknown as void;
}
Upvotes: 1