9

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}
      />
    )
  }
}
Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
  • `innerRef` isn't a standard React property. It must be a `prop` that is used by `Ycomponent` – user2340824 Nov 23 '19 at 12:39
  • Are you using Material UI? In `innerRef` is a legacy feature that was used in MuiV3 [See here.](https://v3.mui.com/css-in-js/api/#withstyles-styles-options-higher-order-component) – dwjohnston Apr 20 '22 at 03:23

1 Answers1

5

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?

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118