'Difference between `ref` and `innerRef` in ReactJS
I am using two class components where I have a method that I am invoking from the parent component. and for this reason, I have to create two references using React.createRef()
. But the problem is one component allows me with ref
attribute and another innerRef
attribute. So I want to know what is the difference.
class X extends Component {
constructor(props) {
super(props);
this.xRef = React.createRef();
this.yRef = React.createRef();
}
render() {
return (
<Xcomponent
classes={classes}
user={user}
ref={this.xRef}
/>
<Ycomponent
classes={classes}
user={user}
innerRef={this.xRef}
/>
)
}
}
Solution 1:[1]
innerRef
is a component instance property, while ref
is a component instance attribute:
When the ref attribute is a callback function, the function receives the underlying DOM element or class instance.
// Access reference within the parent component: this.xRef.current
// Access property within the component: this.props.innerRef.current
<Ycomponent ref={this.xRef} innerRef={this.xRef} />
// coolRef is an ordinary component property, you can name it as you like
<Ycomponent ref={this.xRef} coolRef={this.xRef} />
// access with this.props.coolRef.current within the component.
In conclusion, the custom component Ycomponent
defines the property innerRef
for the developer to pass a reference with it.
For more info see related question: Why, exactly, do we need React.forwardRef?
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 |