3
votes

Hey guys I have an issue where I have a search bar with a dropdown menu. As of right now, I would like to close the dropdown menu whenever an onBlur events occurs on the Search Bar. (which is just an input tag) But I would also like it to detect when it has clicked my drop down menu. And if so, trigger some other function.

Here is my search bar which will call onBlur prop before the onClickLocationSearch prop, which is not what I want because onClickLocationSearch and the onBlur event handle different functions. In other words, I want the onBlur event to check whether it has clicked on another component or not.

Here is the Search Bar with the onBlur event:

<SearchBar
onFocus={this.handleOpenLocationSearch}
placeholder={this.state.placeholder}
onBlur={this.handleCloseLocationSearch}
/>

Here is the Results/Drop down menu.

<Results
onClickLocationSearch={this.handleClickLocationSearch}
/>

onBlur will get called because it gets called regardless of whether you click on the Results component or not.

Here are the functions that they call:

public handleClickLocationSearch() {
    this.setState({queryParam: '/blah'});
    this.setState({ query: '' });
    this.setState({ editing: false });
  }
public handleCloseLocationSearch() {
    this.setState({ editing: false });
    this.setState({ query: '' });
}
  1. I would like to call the handleClickLocationSearch if the user clicks on the Results component and loses focus on the input tag,
  2. If the user loses focus on the input tag and doesn't click on the Results component, call the handleCloseLocationSearch.
1

1 Answers

2
votes

The best solution is to use the 2nd parameter in the onBlur synthetic event to find out what element GAINED focus. There's a pretty good write up on it here.