Slapbox Slapbox - 1 year ago 111
React JSX Question

How can I focus on an element within an imported React component?

I'm importing React-Search-Input and would like to programmatically focus on the text input contained within the component, but it contains no refs and no method to focus on the input.

So because of that, running .focus() on the element, doesn't focus on what I need, which is the text input within the component. It instead focuses on a container element.

Do I have any options here besides forking the project? Thanks!

Answer Source

You can use ReactDOM.findDOMNode to retrieve the element and then call focus on the first child. Something like this:

    ref={(ref) => {ReactDOM.findDOMNode(ref).firstChild.focus()}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download