Search code examples
reactjsref

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} />);
    }


Solution

  • 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.