React - How to pass `ref` from child to parent component?
As per DOC:
You may not use the ref attribute on functional components because they don't have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state.
So i think, if you want to use the ref
, you need to use class
.
Check this: https://github.com/facebook/react/issues/4936
With react^16.0.0 you would use React.createRef(). Using @Timo's answer, it would look like this:
// Dumb:
export default props =>
<input type='number' ref={props.setRef} />
// Smart:
class Parent extends Component {
constructor(props) {
super(props);
this.ref1 = React.createRef()
}
render(){
return <Dumb {...this.props} setRef={this.ref1} />
}
}
You could use the callback syntax for refs:
// Dumb:
export default props =>
<input type='number' ref={props.setRef} />
// Smart:
class Parent extends Component {
constructor(props) {
super(props);
}
setRef(ref) {
this.inputRef = ref;
}
render(){
return <Dumb {...this.props} setRef={this.setRef} />
}
}