Mad-D
Mad-D

Reputation: 4669

Higher Order Component (self) wrapping in React

Good Evening !!

My question title might be off, but here is the problem i'm trying to address. I have a component (Content) which listens for DOM event and call Board (instance which facilitate communication between Containers and their consuming Applications).

import Board from '../Board';

class Content extends React.Component {
    constructor(props){
        super(props);
    }

    componentDidMount(){
        window.addEventListener("message", this.handleCheck, false);
    }

    componentWillUnmount(){
        window.removeEventListener("message", this.handleCheck, false);
    }

    handleCheck =(event) => {
        const { board } = this.props;

        board.call({
            size: event.detail.size,
            panel: event.detail.panel,
            .....
        })
    }

    render(){
        return null
    }
}

I can consume/call Content component as mentioned below,

import Manager from '../../Manager'
const Example = () => (
  <div>
    <Manager>
      <Content pageType="A4" />
    </Manager>
  </div>
);

The Manager component utilizes the Board API to manage call requests, and maintains the state of it's children. The component provided as children to Manager should also support Board prop.

In Example component i would like to call <Content pageType="A4" /> instead of wrapping with <Manager> and somehow use the <Manager> within the Content component definition (inside the Content component to leverage Manager). i.e

const Example = () => (
  <div>
     <Content pageType="A4" />
  </div>
);

Upvotes: 1

Views: 177

Answers (2)

Maxwelll
Maxwelll

Reputation: 2212

Pretty sure you are just looking for the basic HOC implemenation...

function withManager(Component) {
   class WithManager extends React.Component {
     ...withManagerStuff
    render() {
      return <Component/>
    }
   }
   return WithManager;
}

and then where you want to use your components with the shared HOC (ContentWithManager) you can do something like - module.exports = withManager(Content)

Upvotes: 1

thesb
thesb

Reputation: 219

This stuff gets complex quickly.

I may be off, as I am slightly confused with what you are trying to do. However, I think you need to pass the wrapped (child) component to the wrapping (parent) component.

Here are two HOC examples of how to do this:

Note: Examples use redux and react-router, but the same pattern should work without redux or react-router.


Redirect HOC: redirect.hoc.js
Redirect HOC Example: trans.app.container.js

<!-- Redirect HOC Example Code --> 
<Route component={RedirectHoc(MainContentContainer)} />


Authorization HOC: authorization.hoc.js

<!-- Authorization HOC Example Code --> 
<Route exact path="/beer/add" component={AUTHORIZE_ADMIN(BeerAddComponent)}/>

Upvotes: 1

Related Questions