Skip to content

Share ref with multiple ref handlers #13029

Closed
@joaovieira

Description

@joaovieira

Before React 16.3 we were able to proxy the same element ref to multiple listeners, for example, to grab hold of the element for internal purposes and also expose it publicly, like so:

class MyComponent extends Component {
  attachRef = el => {
    this.buttonEl = el;
    this.props.buttonRef(el);
  }

  // Do something with `this.buttonEl`

  render () {
    return <button ref={this.attachRef}>Button</button>;
  }
}

After React 16.3 this is more complicated as the ref prop can be a function or an object:

class MyComponent extends Component {
  buttonRef = React.createRef();

  attachRef = el => {
    this.buttonRef.current = el;
    
    if (typeof this.props.inputRef === 'function') {
      this.props.inputRef(el);
    } else {
      this.props.inputRef.current = el;
    }
  }

  // Do something with `this.buttonRef.current`

  render () {
    return <button ref={this.attachRef}>Button</button>;
  }
}

First, is this the right approach?

And if so, Typescript types say:

interface RefObject<T> {
  readonly current: T | null;
}

Which prevents us from assigning to current. Shouldn't it not be readonly?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions