Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onMouseDown event in react does not trigger state changes but onClick does

Tags:

reactjs

JSX part looks like this:

<span className="header_srh_i_c" onMouseDown={this.toggleSearchbar}>
    <i className="fa fa-search"
        id="searchButton"
        name="searchButton"
     />
 </span>

function in the same component looks like this:

toggleSearchbar(event){
    const eventType = event.type;
    if(this.state.showSearch && this.props.q && length(this.props.q) > 0){
      this.toggleSearching();
    }else{
      console.log("state after", this.state.showSearch)  //false

      this.setState({showSearch:!this.state.showSearch},function (event) {
      console.log("state after", this.state.showSearch) //false
      })
    }
  }

state remains false event after execution of

this.setState({showSearch:!this.state.showSearch},function (event) {
          console.log("state after", this.state.showSearch) //false
          })

However, it works just fine if I use onClick instead of onMouseDown

like image 604
S Khurana Avatar asked Jan 17 '17 13:01

S Khurana


1 Answers

try

this.setState(prev => ({showSearch: !prev.showSearch}), function(){.....})

instead of

this.setState({showSearch:!this.state.showSearch},function (event) {
      console.log("state after", this.state.showSearch) //false
      })
like image 132
Oleh Devua Avatar answered Nov 15 '22 08:11

Oleh Devua