skip to Main Content

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


  1. 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);
    
    Login or Signup to reply.
  2. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search