Higher Order Components In React Example


In React, a Higher Order Component (HOC) is a function that takes a component and returns a new component with additional functionality. HOCs are used to enhance the behavior or appearance of a component without modifying the original component’s code.

Here’s an example of a Higher Order Component (HOC) in React that provides authentication functionality to a component:

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

const withAuth = (WrappedComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        isAuthenticated: false,
      };
    }

    componentDidMount() {
      const token = localStorage.getItem('token');
      if (token) {
        this.setState({ isAuthenticated: true });
      } else {
        this.setState({ isAuthenticated: false });
      }
    }

    render() {
      if (!this.state.isAuthenticated) {
        return <Redirect to="/login" />;
      }
      return <WrappedComponent {...this.props} />;
    }
  };
};

export default withAuth;

In this example, we have an HOC called withAuth that provides authentication functionality to a component. The HOC creates a new class component that checks if the user is authenticated by looking for a token in local storage. If the user is authenticated, the component is rendered with the WrappedComponent passed as props. If the user is not authenticated, the user is redirected to the login page.

Here’s an example of how we can use this HOC to protect a component that requires authentication:

import React from 'react';
import withAuth from './withAuth';

const Profile = (props) => {
  return (
    <div>
      <h1>Profile Page</h1>
      <p>Welcome {props.username}!</p>
    </div>
  );
};

export default withAuth(Profile);

In this example, we have a Profile component that requires authentication to access. We use the withAuth HOC to protect the Profile component by wrapping it with the HOC. This means that the Profile component will only be rendered if the user is authenticated. If the user is not authenticated, they will be redirected to the login page.

Overall, HOCs are a powerful tool for creating reusable and modular components in React. They allow us to enhance the functionality of existing components without modifying their code directly, making it easier to maintain and update our code over time. In this example, we used an HOC to provide authentication functionality to a component, but HOCs can be used for a wide range of other use cases as well.