Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 745
Ed Williams Avatar asked Nov 07 '22 16:11

Ed Williams


1 Answers

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>
      );
    }
  })
}
like image 72
Dekel Avatar answered Nov 14 '22 22:11

Dekel