In this video we are going to learn about Higher Order Components.
A higher-order component (HOC) is an advanced element for reusing logic in React components.
Components take one or more components as arguments, and return a new upgraded component.
Alright, lets create Higher order component.
So switch to the project and here just create a new folder inside the component.
Let say folder name is HOC Inside the HOC folder just create a new component.
Lets component name is Coloured.js.
Now open Coloured.js component and here just write.
Now use this Higher Order Component with and existing component.
So just open User.js component.
Here I am just going to use This Higher order component.
So first of all import the higher order component so write the code as following.
Alright now save the file and lets check.
So in browser go to the url /user/Jennifer.
You can see here the component text color.
If I change the color class here it will apply on this user component.
So in this way you can use Higher order component in react js.
A higher-order component (HOC) is an advanced element for reusing logic in React components.
Components take one or more components as arguments, and return a new upgraded component.
Alright, lets create Higher order component.
So switch to the project and here just create a new folder inside the component.
Let say folder name is HOC Inside the HOC folder just create a new component.
Lets component name is Coloured.js.
Now open Coloured.js component and here just write.
import React from 'react'
const Coloured = (WrappedComponent) => {
return(props)=>{
return(
<div className=\"text-success\">
<WrappedComponent {...props} />
</div>
)
}
}
export default Coloured;
Now use this Higher Order Component with and existing component.
So just open User.js component.
Here I am just going to use This Higher order component.
So first of all import the higher order component so write the code as following.
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);
Alright now save the file and lets check.
So in browser go to the url /user/Jennifer.
You can see here the component text color.
If I change the color class here it will apply on this user component.
So in this way you can use Higher order component in react js.