Paveloosha
Paveloosha

Reputation: 623

How to get 'ref' of wrapped element in react < 16?

My form fields wrapped by a react component individually. This react component comes from 3rd party module. My challenge is to set 'ref' and get that 'ref' outside of that component so I can call .focus on it.

Note: I don't have access to modify code of 3rd party module.

I can't use .createRef and .forwardRef as don't have access to code and importantly not using React 16+

<WrapperComponent/> This component has input field on which I need to set focus from outside.

Structure is like below:

    MyComponent: // Where I want to access the ref

    render() {
        return (
            <div>
                <WrapperComponent id={id} />
            </div>
        );
    }

Wrapper Component (This is a 3rd party component which has input fields inside. May be structure is like below):

    render() {
        return (<input type="text" id={id} />);
    }

Upvotes: 0

Views: 2172

Answers (2)

Estus Flask
Estus Flask

Reputation: 222493

A clean way is to fork third-party component and make it expose a ref.

One workaround is to extend third-party component:

class FirstParty extends ThirdParty {
  inputRef = React.createRef();

  render() {
    const inputReactEl = super.render();
    return React.cloneElement(inputReactEl, { ref: this.inputRef });
  }
}

Another workaround is to wrap it:

class FirstParty extends Component {
  componentDidMount() {
    this.inputDomEl = ReactDOM.findDOMNode(this);
  }

  render() {
    return <ThirdParty {...this.props}/>;
  }
}

In case React 15 is in use, createRef refs can be changed to legacy refs.

Upvotes: 0

UjinT34
UjinT34

Reputation: 4987

You can get a ref to your own div and write some code to find the node you need among its children.

Since you have an id you can just window.document.getElementById(id) to access that node.

Upvotes: 1

Related Questions