Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and exporting HOC in React

I've been research Higher Order Components in react. My requirement is that I have a set components which I need to extend to give them more functionality without rewriting the entire component. In this case, I found out the concept HOC in react where one could extend the component using a pure function. My question is, can I export the extended component as a normal component. For an example

Component which needs to be extended

class foo extends React.Component {
    render(){
        //something
    }
}

export default foo;

HOC component

function bar(foo) {
    render() {
         return <foo {...this.props} {...this.state} />;
    }
}

export default bar;

Am I able to use the component that way? or am I doing it wrong?

like image 226
Imesh Chandrasiri Avatar asked Nov 28 '17 09:11

Imesh Chandrasiri


1 Answers

A HOC would take a component, add some more functionality and return a new component and not just return the component instance,

What you would do is

function bar(Foo) {

   return class NewComponent extend React.Component {
        //some added functionalities here
        render() {
            return <Foo {...this.props} {...otherAttributes} />
        }
   }

}

export default bar;

Now when you want to add some functionality to a component you would create a instance of the component like

const NewFoo = bar(Foo);

which you could now use like

return (
    <NewFoo {...somePropsHere} />
)

Additionally you could allow the HOC to take a default component and export that as a default component and use it elsewhere like

function bar(Foo = MyComponent) {

and then create an export like

const wrapMyComponent = Foo();
export { wrapMyComponent as MyComponent };

A typical use-case of an HOC could be a HandleClickOutside functionality whereby you would pass a component that needs to take an action based on handleClickOutside functionality

like image 73
Shubham Khatri Avatar answered Sep 19 '22 13:09

Shubham Khatri