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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With