React Higher Order Component - call function in the wrapped component from the wrapper component

843 views Asked by At

Assuming I am using the right pattern, I would like to be able to call someFunc() - which is inside <Home/> - from inside <Wrapper/>. See below:

var Home = React.createClass({
  someFunc() {
    console.log('How can I call this from <Wrapper/>?')
  },
  render() {
    return <h1>Hello World</h1>
  }
})

var Wrapper = (Home) => {
  return React.createClass({
    render() {
      return <Home {...this.props}/>
    }
  })
}

var HomeWrapped = Wrapper(Home)

ReactDOM.render(<HomeWrapped/>, document.getElementById('root'))

updated with solution: https://codepen.io/oldgithub/pen/qPOZEj

1

There are 1 answers

0
Dekel On BEST ANSWER

You can use ref for that:

var Wrapper = (Home) => {
  return React.createClass({
    render() {
      return (
          <div>
              <button onClick={() => {this.home.someFunc()}} />
              <Home
                  {...this.props}
                  ref={(c) => this.home = c;}
              />
          </div>
      );
    }
  })
}