hoist-non-react-methods
Copies non-react specific methods from a child component to a parent component
Inspired by @mridgway's hoist-non-react-statics
When wrapping a component (see Higher-Order Components methods that are defined in the child component aren't accessible anymore. This module makes those methods available on the wrapper component's prototype.
Installation
npm install hoist-non-react-methods --save
When is it needed?
Components can have public methods that are accessible through their instance under parent's refs
.
Component { return <input type="text" ref="input" /> } { return thisinput } Component { return <div> <button onClick= thisrefscomposer></button> <Composer ref="composer" /> </div> }
Assuming you have a component which is decorated, the method focus
will be lost, because the ref
will point the decorator component.
@Component { return <input type="text" ref="input" /> } { return thisinput } { return { static displayName = `Wrapper()` { // some specific logic in a decorator } { return <WrappedComponent ref="wrappedComponent" /> } return Wrapper }} Component // this.refs.composer.focus is undefined! { return <div> <button onClick= thisrefscomposer></button> <Composer ref="composer" /> </div> }
This package provides a function that copies all the methods (prototype and static) from the wrapped component to the wrapper, but keeps all react specific methods (e.g. componentDidMount
etc.) untouched.
@Component { // some specific behavior of Composer isn't hoisted to wrapper } { return <input type="text" ref="input" /> } static { } { return thisinput } { return { static displayName = `Wrapper()` { // some specific logic in a decorator, left intact } { return <WrappedComponent ref="wrappedComponent" /> } return }} Component // works! { return <div> <button onClick= thisrefscomposer></button> <Composer ref="composer" /> </div> }
API
The third parameter is a configuration object. Options:
delegateTo
: a function that gets the instance of the wrapper component and returns the instance of the wrapped component (e.g.wrapper => wrapper.refs.child
)hoistStatics: true/false
- controls whether to hoist statics or not
Test
npm installnpm test
License
MIT