Last active
February 16, 2021 10:09
-
-
Save Gaya/746dc6921d234e83a631ab52a62e4c7e to your computer and use it in GitHub Desktop.
Pure Component HOC in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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