0

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?

Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
iPhoneJavaDev
  • 821
  • 5
  • 33
  • 78

2 Answers2

0

Decorators are not supported for function components by default. however, you can do the same thing using a higher-order component (HOC) pattern

const mydecorator = () => (Child: React.ComponentType<any>) => {
  return function DecoratedComponent(props: any) {
    return (
      <div>
        <div>This is my decorator</div>
        <Child {...props} />
      </div>
    );
  };
};
const TestComponent = () => {
  return <div>Test</div>;
};
const DecoratedTestComponent = mydecorator()(TestComponent);
Ahmed Sbai
  • 10,695
  • 9
  • 19
  • 38
0

You have to wrap functional components in the decorator. Either like

const MyComponent: FC = Decorator((props) => {
  return <div>Hello World</div>;
});

https://www.linkedin.com/pulse/using-decorators-react-components-emmanuel-davidson

Or oldschool, by wrapping the export like in the following SO post

export default decorator(component)

How do I rewrite a react component with decorators as a pure function?

Vayne Valerius
  • 158
  • 1
  • 9