17 Feb 2024
Advanced
Higher-Order Components (HOC) in React are functions that accept a component and return a new component with enhanced functionality.
Higher-Order Component (HOC) in React typically looks like this:
jsx Syntax:
const EnhancedComponent = higherOrderComponentFunction(WrappedComponent);
tsx Syntax:
const EnhancedComponent: React.ComponentType<Props> = higherOrderComponentFunction(WrappedComponent);
In the above HOC syntax:
higherOrderComponentFunctionis the Higher-Order Component (HOC) function. It's a function that takes a component (in this case,WrappedComponent) as an argument and returns an enhanced version of that component.WrappedComponentis a React component that is being passed as an argument to thehigherFunction. This component will be enhanced by thehigherFunctionto create a new component, which is assigned tonewComponent.EnhancedComponentrefers to the component returned by the Higher-Order ComponenthigherOrderComponent. This component is the enhanced version of theWrappedComponent, which means it may have additional props, behavior, or functionality provided by the HOC.
Example:
In TypeScript with JSX (.tsx), the syntax for using Higher-Order Components (HOC) remains the same as in JavaScript with JSX. Here's how you can use HOC in a .tsx file:
- higherOrderComponent.tsx
import React from 'react';
// Define a Higher-Order Component (HOC) function
const higherOrderComponent = (WrappedComponent: React.ComponentType<any>) => {
// Enhance the WrappedComponent here
const EnhancedComponent = (props: any) => {
// Enhance props or add additional functionality
return <WrappedComponent {...props} />;
};
return EnhancedComponent;
};
export default higherOrderComponent;
- MyComponent.tsx
import React from 'react';
// Define a regular React component
const MyComponent = (props: any) => {
return <div>{props.message}</div>;
};
export default MyComponent;
- App.tsx
import React from 'react';
import higherOrderComponent from './higherOrderComponent';
import MyComponent from './MyComponent';
// Use the HOC to enhance the component
const EnhancedMyComponent = higherOrderComponent(MyComponent);
// Usage of the enhanced component
const App = () => {
return (
<div>
<EnhancedMyComponent message="Hello, HOC!" />
</div>
);
};
export default App;
In the above example:
WrappedComponentis of typeReact.ComponentType<any>, which means it can accept any React component as an argument.MyComponentis a regular React component.EnhancedMyComponentis the result of applying the HOC (higherOrderComponent) toMyComponent.Appis a component that renders the enhanced component (EnhancedMyComponent).