I have this decorator in a react project:
const mydecorator = () => {
return (Child: any) => {
return class extends React.Component {
...
render() {
return (
<div>
<div>This is my decorator</div>
<Child />
</div>
)
}
}
}
}
If I use it in a class component as follows, it works:
@mydecorator()
class TestComponent extends React.Component {
render() {
return <div>Test</div>
}
}
However, when I use it in a functional component, I got an error
Decorators are not valid here. (ts1206).
@mydecorator()
const TestComponent = () => {
return <div>Test</div>
}
How can I make the decorator work on a functional component?
2
Answers
Decorators are not supported for function components by default. however, you can do the same thing using a higher-order component (HOC) pattern
You have to wrap functional components in the decorator. Either like
https://www.linkedin.com/pulse/using-decorators-react-components-emmanuel-davidson
Or oldschool, by wrapping the export like in the following SO post
How do I rewrite a react component with decorators as a pure function?