How to useES6 Classes in ReactJS
When you need the HOC to have its own state or lifecycle methods, using ES6 classes is the preferred approach.
Example: Below is the code example `withLoadingIndicator`
import React from "react";
// withLoadingIndicator HOC shows a loading
// indicator based on its own state
const withLoadingIndicator = (WrappedComponent) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true };
}
componentDidMount() {
// Mock loading time
setTimeout(() => this.setState({ isLoading: false }),1000);
}
render() {
const { isLoading } = this.state;
return isLoading ? (
<div>Loading...</div>
) : (
<WrappedComponent {...this.props} />
);
}
};
};
// Component to be enhanced
const HelloWorld = () => <div>Hello, world!</div>;
// Enhanced component with loading indicator
const HelloWorldWithLoading = withLoadingIndicator(HelloWorld);
// Usage in App component
function App() {
return <HelloWorldWithLoading />;
}
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} />;
}
};
};