Skip to content

Instantly share code, notes, and snippets.

@danalloway
Last active November 30, 2019 18:02
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 danalloway/0776fa0e21a00a3fad61a52b882d5baf to your computer and use it in GitHub Desktop.
Save danalloway/0776fa0e21a00a3fad61a52b882d5baf to your computer and use it in GitHub Desktop.
HOC FTW
import React from "React"
import hoistNonReactStatic from "hoist-non-react-statics"
const withHOC = hocProps => WrappedComponent => {
// use `hocProps` to configure how the HOC behaves towards it's `WrappedComponent`
const { debug } = hocProps
if (debug) {
console.debug("withHoc is in DEBUG mode")
}
class WithHOC extends React.Component {
render() {
const { forwardedRef, ...restProps } = this.props
return <WrappedComponent {...restProps} ref={forwardedRef} />
}
}
WithHOC.displayName = `WithHOC${WrappedComponent.displayName || WrappedComponent.name || "Component"}`
hoistNonReactStatic(WithHOC, WrappedComponent)
return React.forwardedRef((props, ref) => (
<WithHOC {...props} forwardedRef={ref} />
))
}
export default withHOC
@danalloway
Copy link
Author

danalloway commented Aug 9, 2018

withHOC({ debug: true })(MyComponent)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment