Updated April 14, 2023
Introduction to React Higher Order Component
For adding additional functions to the existing components, Higher order components are used. These components are functions of JavaScript. Higher order components receive data and return values according to the data which makes them pure functions. Whenever the data input changes, the re-running of higher-order components is done with the new data input. This means that whenever we want to change the return values, we just need to change the data accordingly and the Higher order components need not change. Higher-order Components return a new component that is actually wrapped in the original one, which was provided to the function. In this article we will go through multiple examples to understand its working like a simple higher-order component, Text list using React Higher order component, React Higher order component with Loader, Counter using Higher Order Component, Text Display on hover with Higher Order Component. These examples are explained below respectively.
Syntax:
var newData = {
data: 'Welcome',
}
varMyHOC = ComposedComponent => class extends React.Component {
componentDidMount() {
this.setState({
data: newData.data
});
}
export default MyHOC(MyComponent);
Working of React Higher Order Component
Following are the examples are given below:
1. Simple React Higher Order Component
Files required to develop it:
- index.html
- index.js
1. index.html
<div id="root"></div>
2. index.js
import React from 'react';
import { render } from 'react-dom';
const Hello = ({ name }) =><h1>Heyoo {name}!</h1>;
function simpleHOC(WrappedComponent) {
return class extends React.Component{
render() {
return <WrappedComponent {...this.props}/>;
}
}
}
constNewComponent = simpleHOC(Hello);
const App = () =>
<div>
<NewComponent name="Life" />
</div>;
render(<App />, document.getElementById('root'));
Output:
2. Text List using Higher Order Component
Components inside src folder:
- index.js
- messages.json
1. index.js
import React from "react";
import { render } from "react-dom";
import * as data from "./messages.json";
constMessageTemplate = props => {
return (
<div className="message-container">
<p>"{props.text}"</p>
<div className="details-container">
<small>
Texted by <b>{props.sentBy}</b>
</small>
{props.button}
</div>
</div>
);
};
constlikeButtonHOC = WrappedComponent => {
return class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { hasLike: false };
}
handleClick() {
this.setState({
hasLike: !this.state.hasLike
});
}
render() {
constbuttonText = this.state.hasLike ? "Liked ✔" : "👍";
constlikedClass = this.state.hasLike ? "liked" : "";
const button = (
<button className={likedClass} onClick={this.handleClick.bind(this)}>
{buttonText}
</button>
);
return <WrappedComponent button={button} {...this.props} />;
}
};
};
const App = props => {
constMessageContainer = likeButtonHOC(MessageTemplate);
return (
<div>
<h2>Text List</h2>
{props.messages.map((message, i) => (
<MessageContainer
key={`message-${i}`}
text={message.text}
sentBy={message.sentBy}
/>
))}
</div>
);
};
render(<App messages={data.messages} />, document.getElementById("root"));
2. messages.json
{
"messages": [
{
"text": "Hey! Wanna Catch Up Tonight",
"sentBy": "Ankush"
},
{
"text": "Heyoo Bro! 🙋 How are you?",
"sentBy": "Adarsh"
},
{
"text": "Hello My World! 🌏",
"sentBy": "Rahul"
}
]
}
Output:
3. React Higher Order Component with Loader
Components inside src folder:
- App.js
- hoc.js
- index.js
- styles.css
1. App.js
import React from "react";
import ReactDOM from "react-dom";
import HOC from "./hoc";
import "./styles.css";
class WrapApp extends React.Component {
constructor(props) {
super(props);
this.state = { data: {} };
}
render() {
console.log("here--->", this.props);
return (
<div>
<h1>EDUCBA</h1>
<h2>Welome to best platofrm for Latest Courses and Trainings</h2>
<h3>We provide trainings related to Data Science, Data Analysis, and every emaerging technology</h3>
</div>
);
}
}
const App = HOC(WrapApp);
export default App;
2. hoc.js
import React
, { Component } from "react";
let HOC = WComponent => {
return class Loader extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response =>response.json())
.then(data => {
this.setState({ data, loading: false });
});
}
render() {
console.log("i", this.state.data);
if (this.state.data.length === 0) {
return <h1>Content is loading...</h1>;
} else {
return <WComponent {...this.state} />;
}
}
};
};
export default HOC;
3. index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
constrootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
4. styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif
text-align: center;
}
Output:
4. Counter using React Higher Order Component
Components inside src folder:
- index.js]
- styles.css
1. index.js
import React from "react";
import { render } from "react-dom";
constwithCounter = Component =>
class Hoc extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
update = type => {
if (type === "Inc") {
this.setState(({ count }) => ({ count: count + 1 }));
} else if (type === "Dec") {
this.setState(({ count }) => ({ count: count - 1 }));
}
};
render() {
return <Component {...this.state} {...this.props} update={this.update} />;
}
};
const Counter = ({ count, update }) => (
<div>
<h1>Simple Counter</h1>
<button onClick={() => update("Inc")}>Increase the Value</button>
{ count }
<button onClick={() => update("Dec")}>Decrease the Value</button>
</div>
);
constCounterExample = withCounter(Counter);
render(<CounterExample />, document.getElementById("root"));
2. styles.css
.App {
font-family: arial;
text-align: center;
}
Output:
5. Text Display on Hoover with React Higher Order Component
A component inside src folder:
- hocs folder
- MyComponent.js
- index.js
- styles.css
A component inside hocs folder:
- index.js
- withTooltip.js
1. index.js (in hocs folder)
export * from "./withTooltip";
2. withTooltip.js (in hocs folder)
import React from "react";
export constwithTooltip = WrappedComponent =>({ tooltipText, ...props }) => (
<div title={tooltipText}>
<WrappedComponent {...props} />
</div>
);
3. MyComponent.js
import React from "react";
import { withTooltip } from "./hocs";
constMyComponent = ({ label }) =><div>{label}</div>;
export default withTooltip(MyComponent);
4. index.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import MyComponent from "./MyComponent";
function App() {
return (
<div className="App">
<MyComponent
tooltipText={"Hey Sweetie! You are so beautiful"}
label={"Hover on this text, so that you can see the secret Message"}
/>
</div>
);
}
constrootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
5. styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
Recommended Articles
This is a guide to React Higher Order Component. Here we also discuss the introduction and working of react higher order component along with examples and its code implementation. You may also have a look at the following articles to learn more –