React.js Higher-Order Components
Higher-order components or HOC is the advanced method of reusing the component functionality logic. It simply takes the original component and returns the enhanced component.
Syntax:
const EnhancedComponent = higherOrderComponent(OriginalComponent);
Reason to use Higher-Order component:
- Easy to handle
- Get rid of copying the same logic in every component
- Makes code more readable
Creating React Application:
-
Step 1: Create a React application using the following command.
npx create-react-app foldername
-
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Project Structure:
Example 1: Let say, we need to reuse the same logic, like passing on the name to every component.
Name.js
import React from 'react'
const EnhancedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {
render() {
return <OriginalComponent name= "GeeksforGeeks" />
}
}
return NewComponent
}
export default EnhancedComponent;
|
App.js
import React from "react" ;
import "./App.css"
import EnhancedComponent from './Name'
class App extends React.Component {
render() {
return <h1>{ this .props.name}</h1>
}
}
export default EnhancedComponent(App);
|
Output: Here, we pass the name as a prop with the value for calling out from different components.
Example 2: In this example let’s implement some logic. Let’s make a counter app. In HighOrder.js, we pass the handleclick and show props for calling the functionality of the component.
Project Structure:
HighOrder.js
import React from 'react'
const EnhancedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {
constructor(props) {
super (props);
this .state = { count: 0 };
}
handleClick = () => {
this .setState({ count: this .state.count + 1 });
}
render() {
return <OriginalComponent
handleclick={ this .handleClick}
show={ this .state.count} />
}
}
return NewComponent
}
export default EnhancedComponent
|
App.js
import React from 'react'
import "./App.css"
import EnhancedComponent from './HighOrder'
class App extends React.Component {
render() {
const { show, handleclick } = this .props
return <button onClick={handleclick}>{show}
</button>
}
}
export default EnhancedComponent(App);
|
Output:
Reference:https://reactjs.org/docs/higher-order-components.html
Last Updated :
22 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...