Approach to implement Higher Order Component in React
- First define a function that accepts a component as its argument.
- Inside the HOC, create a new component class or function that wraps the input component.
- Implement any additional logic or state that you want the original component to have.
- Return the enhanced component from the HOC function.
Example: Illustration to showcase the use of Higher Order Component in react.
// App.js
import React from 'react';
// Higher-Order Component
const withHoverEffect = (WrappedComponent) => {
return class extends React.Component {
state = {
isHovered: false,
};
handleMouseEnter = () => {
this.setState({ isHovered: true });
};
handleMouseLeave = () => {
this.setState({ isHovered: false });
};
render() {
return (
<div
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
>
<WrappedComponent {...this.props}
isHovered={this.state.isHovered} />
</div>
);
}
};
};
// Component without hover effect
const Button = ({ isHovered, onClick }) => {
return (
<button style={{ backgroundColor: isHovered ? 'white' : 'red' }}
onClick={onClick}>
Click Me
</button>
);
};
// Enhance Button component with hover effect using HOC
const ButtonWithHoverEffect = withHoverEffect(Button);
const App = () => {
const handleClick = () => {
alert('Button clicked!');
};
return (
<div>
<h1>Example to showcase <br></br> Higher-Order Component</h1>
<ButtonWithHoverEffect onClick={handleClick} />
</div>
);
};
export default App;
Output:
Why would you use a Higher-Order Component in React ?
A Higher-Order Component (HOC) in React is used to share common functionality between multiple components. It’s like a function that takes a component as an argument and returns a new enhanced component with added features.
By offering a pattern for reusing component logic, HOCs help in crafting more maintainable and cleaner React applications. This article simplifies the concept of HOCs, showcases their benefits, and walks through an example to highlight their practical application.