React JS Tutorial - Higher Order Components

In this tutorial, we will learn about Higher Order Components (HOCs). A HOC is an advanced element that enables reusing logic in React components. It takes one or more components as arguments and returns a new, upgraded component.

Creating a Higher Order Component

Let's create a Higher Order Component. Switch to your project and create a new folder inside the components folder. Let's name the folder "HOC". Inside the HOC folder, create a new component, for example, "Coloured.js".

Open the Coloured.js component and write the following code:


import React from 'react'

const Coloured = (WrappedComponent) => {
return(props)=>{
return(
<div className="text-success">
<WrappedComponent {...props} />
</div>
)
}
}

export default Coloured;

Using the Higher Order Component

Now, let's use this Higher Order Component with an existing component. Open the User.js component. We will use the Higher Order Component here. First, import the Higher Order Component by writing the code as follows:


import React, { Component } from 'react'
import Colourd from '. /HOC/Coloured';

class User extends Component {
state = {
name:null
}
componentDidMount(){
let name = this.props.match.params.name;
}

render() {
return (
<div>
<h3>{this.state.name}</h3>
</div>
)
}
}

export default Colourd(User);

Save the file and let's check the result. In the browser, go to the URL "/user/Jennifer". You should see the component text color applied. If you change the color class here, it will be applied to the User component.

In this way, you can use Higher Order Components in React JS to reuse logic and enhance your components.