Slapbox Slapbox - 3 months ago 18
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

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

<SearchInput
    className="search-input"
    onChange={this.searchUpdated}
    ref={(ref) => {ReactDOM.findDOMNode(ref).firstChild.focus()}}
/>