Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React input.focus() called by `ref` also invoking `onBlur` event

I have an input element in React that I want to set onFocus, onBlur, and ref callbacks for. Setting the ref callback is having the unwanted behavior of firing the onBlur event when I run input.focus() inside of it.

<input
    onFocus={() => {
        props.startSearch(); // set props.active === true
    }}
    onBlur={() => {
        props.endSearch(); // set props.active === false
    }}
    ref={(input) => {
        if (input && props.active) {
            input.focus();
        }
    }}
/>

I have another component that dispatches an action setting props.active to true. This should focus the input component. However, when the component mounts, the input's onBlur callback fires unexpectedly:

ref => onFocus => onBlur

This is setting props.active to true, but then immediately setting it false (because props.endSearch fires).

When I comment out input.focus() and manually click to focus the input, I get onFocus => ref, which is the desired behavior. This clearly does not have the effect of "auto-focusing" the input, however.


Why is input.focus() triggering onBlur to fire and how can I prevent this?

like image 740
Himmel Avatar asked Nov 09 '22 10:11

Himmel


1 Answers

Try using autoFocus. Like:

<input ref="searchBox" onFocus={props.startSearch} onBlur={props.endSearch} autoFocus={props.active} />

Edit:

Also, in your componentDidUpdate do (note the updated ref above):

if (this.props.active) {
  this.refs.searchBox.focus();
}
like image 110
Jack Avatar answered Nov 14 '22 21:11

Jack