FabioCosta
FabioCosta

Reputation: 2749

React Recompose call a bound method of an enhaced component

Using recompose is it possible to call a bound method of an enhaced component? For instance the onClick on the example below on "SomeOtherComponent"

class BaseComponent extends Component {
  constructor (props) {
    super(props)
    this.myBoundMethod = this._myBoundMethod.bind(this)
  }
  _myBoundMethod () {
    return this.something
  }
  render () {
    return (<h1>{'Example'}</h1>)
  }
}

const Enhaced = compose(
  /* Any number of HOCs ...  
    lifecycle,
    withProps,
    withStateHandlers
  */
)(BaseComponent)

class SomeOtherComponent extends Component {
  constructor (props) {
    super(props)
    this.handleClick = this._handleClick.bind(this)
  }
  _handleClick () {
    console.log(this._enhacedComponent.myBoundMethod())
  }
  render () {
    <div>
      <Enhaced ref={(c) => {this._enhacedComponent = c}} />
      <button onClick={this.handleClick}>Click</Button>
    </div>
  }
}

I'm aware of hoistStatics but I don't know how to make it for a bound method.

Upvotes: 1

Views: 258

Answers (1)

wuct
wuct

Reputation: 10477

hoistStatics only hoists static properties, but what you need is instance methods.

Here is a way to achieve what you want in Recompose. First, rename ref callback to, for example, forwardedRef:

<Enhaced fowardedRef={(c) => { this._enhacedComponent = c }} />

Then, use withProps as the last HOC to rename fowardedRef to ref:

const Enhaced = compose(
  /* ... other HOCs ... */
  withProps(({ fowardedRef }) => ({ ref: fowardedRef  }))
)(BaseComponent)

Now, the ref callback is passed to BaseComponent.

The whole running example is here https://codesandbox.io/s/6y0513xpxk

Upvotes: 1

Related Questions