React/ReactJS: Higher Order Component (HOC) Example
In React, a Higher Order Component is a function which takes in a component as an argument and returns a new component. This is a design pattern which came out of React's compositional nature and is akin to a higher-order function in JavaScript.
A HOC Example
In the code below, HOC is a higher order component to which the function component <Hello/> is passed as an argument. A new component is returned with its contents coloured red.
In the first section below, the HOC component returns a function component.
import React, { Component } from "react";
function Hello() {
return (
<div>Hello!</div>
)
}
function HOC(Fn) {
return () => {
return (
<div style={{color: "red"}}>
<Fn/>
</div>
)
}
}
let H = HOC(Hello);
function App() {
return (
<>
<H/>
</>
);
}
export default App;
In this next section, the HOC component returns a class component.
import React, { Component } from "react";
function Hello() {
return (
<div>Hello!</div>
)
}
function HOC(Fn) {
return class extends Component {
render() {
return (
<div style={{color: "red"}}>
<Fn/>
</div>
)
}
}
}
let H = HOC(Hello);
function App() {
return (
<>
<H/>
</>
);
}
export default App;