Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Higher-Order Components (HOC) in React

In this chapter, you will learn about what are Higher-Order Components (HOC) in React.

  1. The Higher-Order Components (HOC) is a function which receives the component and returns the new component
  2. In other words, it wraps another component.
  3. It does not contain any of its own logic
  4. It accepts the wrapped component and returns the component function.

Now we will write an example to understand HOC properly. Let’s create the following directory structure,

Step 1:
Create the file src/components/manager/Manager.js if you have it already paste the below code snippet

import React from "react";
import './Manager.css'
const manager = props => {
  return (
    <div>
      {props.isManagerLoggedin ? (
        <div>
          <h2>Welcome to your dashboard</h2>
          {props.employee.map(item => (
            <li key={item.name}> Name: {item.name}, ID: {item.empId}</li>
          ))}
          <button onClick={props.logout}>Logout</button>
        </div>

      ) : (
        <div>
          <h2>Please login</h2>
          <button onClick={props.login}>Login</button>
        </div>
      )}
    </div>
  );
};

export default manager;

Step 2:
Create the file src/components/hoc/Container.js if you have it already paste the below code snippet

import React from 'react';

const container = (props) => (
    <div className={props.divClassName}>
        {props.children}
    </div>
);

export default container;

Step 3:
Create the file App.js if you have it already paste the below code snippet

import React, { Component } from 'react';
import './App.css';
import Manager from './components/manager/Manager';
import Container from './components/hoc/Container';
class App extends Component {
  constructor(props) {
    super(props);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.state = { 
      isManagerLoggedin: false,
      employee: [
        {name:'Stark', empId:'123'},
        {name:'John', empId:'124'},
        {name:'Mickel', empId:'125'},
        {name:'Clark', empId:'126'}
      ]
    };
  }

  componentDidMount() {}

  login = e => {
    this.setState({ isManagerLoggedin: true });
  };

  logout = e => {
    this.setState({ isManagerLoggedin: false });
  };

  render() {
    return (
      <Container divClassName='App'>
        <h1>Welcome to react JS tutorial</h1>
        <Manager
          isManagerLoggedin={this.state.isManagerLoggedin}
          login={this.login}
          logout={this.logout}
          employee={this.state.employee}
        />
      </Container>
    );
  }
}

export default App;

Now look at the URL: http://localhost:3000/
You should be able to see the output

 

One thought on “Higher-Order Components (HOC) in React

Comments are closed.