I'm making an Autocomplete component in React which shows a dropdown of suggested completions as you type into a text box. Clicking on a suggestion should fire a callback, and the dropdown should disappear when the text box loses focus. The problem is that the onBlur event for the text box fires before the onClick event for the the suggestion, so what happens is:
this.setState(this.getInitialState())
What's the best way to solve this without resorting to a hack like onBlur={() => setTimeout(() => this.setState(this.getInitialState()), 100)}?
Found a very simple solution: the mousedown event fires for the result item being clicked before blur fires for the text input. Furthermore if the mousedown callback calls event.preventDefault(), it prevents the blur event from firing for the input, but doesn't prevent the future click event from firing on the result item once mouseup occurs. So, long story short, simply adding this handler to the result item fixes everything: onMouseDown={event => event.preventDefault()}
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