Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
      />
    )
  }
}
like image 796
Fatema tuz johura Avatar asked Nov 23 '19 12:11

Fatema tuz johura


1 Answers

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?

like image 183
Dennis Vash Avatar answered Nov 11 '22 01:11

Dennis Vash