'How to implement a forward ref in React0.14?
I want to get the ref of the children's component.The nested relationship between the components is shown below:
<Demo1 /> ---> <Demo2 /> ---> <Demo3 />
how to get the ref of Demo3 in Demo1?
Solution 1:[1]
You can pass the ref inside of the props:
// -- sub-sub component
var SubSub = React.createClass({
render: function() {
return <div><sub ref={ this.props.subSubRef }>Sub-sub component</sub></div>;
}
});
// -- sub component
var Sub = React.createClass({
render: function() {
return <div><em>Sub component</em><SubSub subSubRef={ this.props.subRef } /></div>;
}
});
// -- root component
var Main = React.createClass({
render: function() {
// -- get the ref from the child
const refCallback = function( domRef ){
this._subSubDomRef = domRef;
}.bind( this );
// -- example: accessing the dom element in some way
const handleClick = function(){
if( this._subSubDomRef ){
this._subSubDomRef.innerHTML = this._subSubDomRef.innerHTML + '.';
}
}.bind( this );
// --
return <div>
<strong onClick={ handleClick }>Main component</strong>
<Sub subRef={ refCallback } />
</div>;
}
});
(Note that you might run into conflicts in the case that some library that you are using, uses the same prop name as you do. That's one reason why forwardRef is recommended)
Further information:
The official React documentation mentions forwarding refs prior to the availability of forwardRef
under exposing-dom-refs-to-parent-components,
and recommends the example in dom_ref_forwarding_alternatives_before_16.3.md.
Unfortunately this example uses createRef, which is also not available before v16.3.
You need to follow the comments there and adapt the example accordingly.
The React documentation for v0.14 can be found at web.archive.org.
forwardRef and createRef were introduced in version 16.3.0 (March 29, 2018):
- 2018-02-06 createRef (8dc8f88d5ae9fb96934ba43e3842b5dcf4074afd)
- 2018-03-14 forwardRef 16.3.0-alpha.2 (bc70441c8b3fa85338283af3eeb47b5d15e9dbfe)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kca |
