Slapbox Slapbox - 1 month ago 6x
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!


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()}}