Higher order components in React.js

React JSJavascript LibraryFront End Technology

Higher order component in short called as hoc. It’s a pattern which receives a component and returns a new component with add-on features to it.

//hoc is the name of a custom JavaScript function

const AddOnComponent= hoc(SimpleComponent);

We use component with state and/or props to build an UI. Similar way a hoc builds a new component from the provided component.

Use of hoc is making a cross cutting concerns in React. The components will take care of individual responsibility of single tasks while hoc functions will take care of cross cutting concerns.

Connect function from redux is an example of hoc.

A practical example of hoc

Display welcome message to customer or admin based on user type.

Class App extends React.Component{
   render(){
      return (
         <UserWelcome message={this.props.message} userType={this.props.userType} />
      );
   }
}
Class UserWelcome extends React.Component{
   render(){
      return(
         <div>Welcome {this.props.message}</div>
      );
   }
}
const userSpecificMessage=(WrappedComponent)=>{
   return class extends React.Component{
      render(){
         if(this.props.userType==’customer’){
         return(
            <WrappedComponent {…this.props}/>
         );
         } else {
            <div> Welcome Admin </div>
         }
      }
   }
}

export default userSpecificMessage(UserWelcome)

In the UserWelcome, we are just displaying message to user passed by parent component App.js.

The UserComponent is wrapped by hoc userSpecificMessage which received the props from wrapped component i.e. UserComponent

The hoc userSpecificMessage decides which message to display based on the type of user.

If the type of the user is customer it displays the message as it is. But if the user is not customer then it displays a Welcome Admin message by default.

With this way we can add the common functionality required by components in hoc and use it whenever required.

It allows code reuse and keeps the components clean with the individual tasks only.

raja
Published on 05-Sep-2019 11:23:53
Advertisements