Ref to a child component through HOC
by Vladimir Kutepov
HTML
<script src="https://unpkg.com/react@15.3.2/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<div id="root"></div>
Babel + JSX
class Child extends React.Component {
componentDidMount() {
this.props.onRef(this)
}
componentWillUnmount() {
this.props.onRef(null)
}
method() {
console.log('do stuff')
}
render() {
return <h1>Hello World!</h1>
}
}
// Any higher-order component (HOC), for examle:
// withStyles https://github.com/kriasoft/isomorphic-style-loader
// connect https://github.com/reactjs/react-redux
// etc.
class EnhancedChild extends React.Component {
render() {
return <Child {...this.props} />
}
}
class Parent extends React.Component {
onClick = () => {
this.child.method() // do stuff
};
render() {
return (
<div>
<EnhancedChild onRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.method()</button>
</div>
);
}
}
ReactDOM.render(<Parent />, document.getElementById('root'))