Search code examples
reactjstypescriptbluronblurmui

React Typescript Mui `onBlur` firing every change


I am writing a front-end app in Typescript and React and am using MUI. I have the following code for a form:

<TextField
  label="Password"
  value={this.state.password}
  placeholder="Choose a password"
  type="password"
  onChange={(event: any) => this.setState({
    password: event.target.value
  })}
  onBlur={console.log('here')}
  error={this.state.passwordError}
/>

With this code, every time I click a key, onBlur gets fired. Isn't it only supposed to fire when I leave the form?


Solution

  • Would be helpful to see the onblur function. It doesn't look like you want to pass anything to it, so simply changing the line onBlur={this.onblur()} to onBlur={this.onblur} should do the trick.

    However, if your function looks like this

    onblur() {
    ...
    }
    

    then you should bind the context to it ('this'). Instead, I'd suggest going for

    onblur = event => {
    ...
    }
    

    which will have the context already binded.