Skip to content

Instantly share code, notes, and snippets.

@foxundermoon
Forked from Restuta/HOC.js
Created February 1, 2020 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxundermoon/8c478dc52fc2b780ee732a07a28f1945 to your computer and use it in GitHub Desktop.
Save foxundermoon/8c478dc52fc2b780ee732a07a28f1945 to your computer and use it in GitHub Desktop.
React HOC (Higher Order Component) Example
/* HOC fundamentally is just a function that accepts a Component and returns a Component:
(component) => {return componentOnSteroids; } or just component => componentOnSteroids;
Let's assume we want to wrap our components in another component that is used for debugging purposes,
it just wraps them in a DIV with "debug class on it".
Below ComponentToDebug is a React component.
*/
//HOC using Class
//it's a function that accepts ComponentToDebug and implicitly returns a Class
let DebugComponent = ComponentToDebug => class extends Component {
render() {
return (
<div className="debug">
<ComponentToDebug {...this.props}/>
</div>
);
}
};
//similar HOC using pure function
//it's a function that accepts ComponentToDebug and explicitly returns a Functional component
let DebugComponent = (ComponentToDebug) => {
return (props) => (
<div className="debug">
<ComponentToDebug {...props}/>
</div>
);
};
//above component can be simplified omitting extra () around parameters and using implicit return
let DebugComponent = ComponentToDebug => (
props => (
<div className="debug">
<ComponentToDebug {...props}/>
</div>
)
);
//or even further omitting extra ()
let DebugComponent = ComponentToDebug => props => (
<div className="debug">
<ComponentToDebug {...props}/>
</div>
);
//finally any definition can be used like that:
DebugComponent(MyComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment