Creating and using higher-order components (HOCs) in React involves creating a function that takes a component as an argument and returns a new component with enhanced functionality.
To create a higher-order component, follow these steps:
Here's an example of a simple HOC that adds a "isLoading" prop to a component:
const withLoading = (WrappedComponent) => {
return class WithLoading extends React.Component {
render() {
const { isLoading, ...props } = this.props;
if (isLoading) {
return <div>Loading...</div>;
}
return <WrappedComponent {...props} />;
}
}
}
To use the HOC, you simply wrap your component with the HOC function:
const EnhancedComponent = withLoading(MyComponent);
// Then use EnhancedComponent just like you would use MyComponent
<EnhancedComponent isLoading={true} />
In this example, the "withLoading" HOC adds a "isLoading" prop to the component it enhances, allowing you to conditionally render a loading message based on the value of that prop.
HOCs are a powerful way to reuse and share functionality across components in a React application. They allow you to separate concerns, enhance components with additional features, and keep your code DRY.