Friday, 29 April 2022

HOC Example

 Create HOCHome class and write following code in it


import React, { Component } from "react";

import Counter from "./Counter";

import Hover from "./Hover";


class HOCHome extends Component {

  render() {

    return (

      <div className="container text-center mt-5">

        <div className="row">

          <Counter />

        </div>

        <div className="row mt-5">

          <Hover />

        </div>

      </div>

    );

  }

}

export default HOCHome;

Create HOC.js and write following code in it

import React from "react";

const hoc = (Component) => {

  class NewComponent extends React.Component {

    constructor(props) {

      super(props);

      this.state = {

        count: 0,

      };

    }

    updateCount = () => {

      this.setState({

        count: this.state.count + 1,

      });

    };

    render() {

      return (

        <Component count={this.state.count} updateCount={this.updateCount} />

      );

    }

  }

  return NewComponent;

};

export default hoc;

Create Counter.js and write following code in it

import React, { Component } from "react";

import hoc from "./HOC";


class Counter extends Component {

  render() {

    return (

      <div className="container">

        <p className="display-6">Clicked me {this.props.count} times</p>

        <button className="btn btn-primary" onClick={this.props.updateCount}>

          Update Count

        </button>

      </div>

    );

  }

}

export default hoc(Counter);

Create Hover.js and write following code in it

import React, { Component } from "react";

import hoc from "./HOC";


class Hover extends Component {

  render() {

    return (

      <div className="container">

        <p className="display-6 lead" onMouseOver={this.props.updateCount}>

          Hovered me {this.props.count} times

        </p>

      </div>

    );

  }

}

export default hoc(Hover);

No comments:

Post a Comment