DEV Community

IHesamI
IHesamI

Posted on

Decorator design pattern in React

Greetings, in this article we will be discussing the implementation of the decorator design pattern in React. The decorator design pattern involves wrapping objects and adding new functionalities to them. For instance, if you are working on a store management system within your React application, you can utilize this design pattern to interact with the store manager and access data.

We will proceed to the implementation stage, starting with creating a Wrapper function that serves as the decorator.

import { FC } from "react";

function Wrapper<T>(ReactComponent: FC<T>) {
    function ComponentWrapper(props: T & JSX.IntrinsicAttributes) {
        return <ReactComponent {...props} />
    }
    return ComponentWrapper;
}

export default Wrapper;
Enter fullscreen mode Exit fullscreen mode

In the code provided, the Wrapper function acts as a decorator for the ReactComponent, which is a functional component in React. The ComponentWrapper serves as the parent component that interacts with the ReactComponent as its child. You can use any hooks within the ComponentWrapper. Let's now use the Wrapper.

import { FC } from 'react';
import Wrapper from './Wrapper';

type props = { title: string; }

const Header: FC<props> = ({ title }) => {
    return (
        <div>
            {title}
        </div>
    );
}

export const HeaderComponent = Wrapper<props>(Header);
export default HeaderComponent;
Enter fullscreen mode Exit fullscreen mode

The code above demonstrates the utilization of the decorator that was created earlier. The Header is a basic react component that is enclosed within the Wrapper component. This component can be utilized just like any other component.

import HeaderComponent from './Header'

function App() {

  return (
    <>
      <HeaderComponent title='Hello DEV.to' />
    </>)
}

export default App


Enter fullscreen mode Exit fullscreen mode

The example above demonstrates how the HeaderComponent is utilized.

Decorator is a robust design pattern commonly found in various JavaScript frameworks such as Angular or NestJS. By implementing this straightforward approach, decorators can also be incorporated into React.

Thank you for taking the time to read this. I hope you found this post useful. Please feel free to share your thoughts in the comments section.

Top comments (0)