Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delayed onBlur callback

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:

  1. Click on item
  2. Text box loses focus => this.setState(this.getInitialState())
  3. Component rerenders, with no suggestions box because state has been cleared
  4. The click event lands on the empty space where the suggestion item used to be

What's the best way to solve this without resorting to a hack like onBlur={() => setTimeout(() => this.setState(this.getInitialState()), 100)}?

like image 465
Tom Crockett Avatar asked Aug 24 '16 23:08

Tom Crockett


1 Answers

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

like image 110
Tom Crockett Avatar answered Sep 27 '22 19:09

Tom Crockett