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}
/>
)
}
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With