Skip to content

Instantly share code, notes, and snippets.

@Gaya
Last active February 16, 2021 10:09
Show Gist options
  • Save Gaya/746dc6921d234e83a631ab52a62e4c7e to your computer and use it in GitHub Desktop.
Save Gaya/746dc6921d234e83a631ab52a62e4c7e to your computer and use it in GitHub Desktop.
Pure Component HOC in React
import React from 'react';
const someProp = 'We want to pass this as a prop';
// hip and short notation
export const wrapComponent = (UncomposedComponent) => (props) => <UncomposedComponent {...props} someProp={someProp} />;
// Or broken down:
// a factory which wraps a component
export function wrapComponent(UncomposedComponent) {
// this is actually a pure component
return function ComposedComponent(props) {
return <UncomposedComponent {...props} someProp={someProp} />;
}
}
// usage:
function wantSomeProp(props) {
return <div>{ props.someProp }</div>;
}
// wrapComponent add `someProp` to props of `wantSomeProp`
const gotSomeProp = wrapComponent(wantSomeProp);
// render
<gotSomeProp />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment