Function that Returns a Function
This approach is useful for adding simple enhancements or props to a component. It’s the most straightforward way to implement an HOC.
Example: Below is the code example using `withExtraProps`:
import React from 'react';
// withExtraProps HOC adds additional props to the wrapped component
const withExtraPrimport React from "react";
// withExtraProps HOC adds additional props to the wrapped component
const withExtraProps = (WrappedComponent) => (props) => {
const extraProps = { extraProp: "This is an extra prop!" };
return <WrappedComponent {...props} {...extraProps} />;
};
// Simple component that displays props
const DisplayPropsComponent = (props) => (
<div>
<h1>
{Object.entries(props).map(([key, value]) => (
<p key={key}>{`${key}: ${value}`}</p>
))}
</h1>
</div>
);
// Enhanced component with extra props
const EnhancedComponent = withExtraProps(DisplayPropsComponent);
// Usage in App component
function App() {
return <EnhancedComponent someProp="This is some prop" />;
}
export default App;
ops = (WrappedComponent) => (props) => {
const extraProps = {extraProp: 'This is an extra prop!'};
return <WrappedComponent {...props} {...extraProps} />;
};
// Simple component that displays props
const DisplayPropsComponent = (props) => (
<div>
<h1>
{Object.entries(props).map(([key, value]) => (
<p key={key}>{`${key}: ${value}`}</p>
))}
</h1>
</div>
);
// Enhanced component with extra props
const EnhancedComponent = withExtraProps(DisplayPropsComponent);
// Usage in App component
function App() {
return <EnhancedComponent someProp="This is some prop" />;
}
export default App;
Output:
How to use HOCs to reuse Component Logic in React ?
In React, making reusable components keeps your code neat. Higher-order components (HOCs) are a smart way to bundle and reuse component logic. HOCs are like magic functions that take a component and give you back an upgraded version with extra powers or information.
HOCs can be implemented in a few different ways, depending on the requirements in the following ways:
Table of Content
- Function that Returns a Function
- Using ES6 Classes
1. Function that Returns a Function: This is the most common approach where the HOC is a function that accepts a component and returns a new component that renders the original component with enhanced props.
Syntax:
const withData = (WrappedComponent) => (props) => {
// Enhanced logic here
return <WrappedComponent {...props} />;
};
2.Using ES6 Classes: Sometimes, you might need the HOC to maintain its own state or lifecycle methods. In such cases, extending React.Component in the HOC can be beneficial.
Syntax:
const withSubscription = (WrappedComponent, selectData) => {
return class extends React.Component {
// Implement lifecycle methods and state here
render() {
return <WrappedComponent {...this.props} />;
}
};
};