Create a Higher Order Component (HOC) using React

Tiempo de lectura: 2 minutos

In React, this type of component is known as a “Higher Order Component” or “HOC”.

An HOC is a function that takes a component and returns another component that usually provides additional functionality to the original component.

Suppose we want to create an HOC called WrapperComponent that wraps another component called WrappedComponent and provides it with some additional functionality.

For example, we might want to provide a red border around WrappedComponent. Here’s how to do it:

import React from 'react';

// Define our HOC
const WrapperComponent = (WrappedComponent) => {
  // Return a new component
  return class extends React.Component {
    render() {
      // Here we can add any additional logic before or after rendering the wrapped component
      return (
        <div style={{ border: '2px solid red', padding: '10px' }}>
          {/* Render the wrapped component and pass all the props */}
          <WrappedComponent {...this.props} />
        </div>
      );
    }
  };
};

// Create a component we want to wrap
const MyComponent = (props) => {
  return (
    <div>
      <h2>Wrapped Component</h2>
      <p>Prop: {props.prop}</p>
    </div>
  );
};

// Wrap MyComponent with our HOC
const WrappedMyComponent = WrapperComponent(MyComponent);

// Use WrappedMyComponent in our app
const App = () => {
  return (
    <div>
      <h1>App with Wrapped Component</h1>
      <WrappedMyComponent prop="Hello!" />
    </div>
  );
};

export default App;

In this example, WrapperComponent is a function that takes WrappedComponent as an argument and returns a new component that wraps WrappedComponent with a red border. Then, we use WrapperComponent to wrap our MyComponent component and create WrappedMyComponent.

Finally, we use WrappedMyComponent in our application.

Leave a Comment