Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using onBlur with JSX and React

I am trying to create a password confirmation feature that renders an error only after a user leaves the confirmation field. I'm working with Facebook's React JS. This is my input component:

<input
    type="password"
    placeholder="Password (confirm)"
    valueLink={this.linkState('password2')}
    onBlur={this.renderPasswordConfirmError()}
 />

This is renderPasswordConfirmError :

renderPasswordConfirmError: function() {
  if (this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

When I run the page the message is not displayed when conflicting passwords are entered.

like image 331
user3862066 Avatar asked Jul 21 '14 19:07

user3862066


People also ask

How do you use onBlur in react JS?

onBlur triggers when focus is lost from the input element in context. In React. js, we bind event handlers by passing a method defined in the component to be called accordingly. .bind(this) is called in order to retain the value of this and expose component methods within the event handler function such as this.

What is the difference between onBlur and onChange?

onChange is when something within a field changes eg, you write something in a text input. onBlur is when you take focus away from a field eg, you were writing in a text input and you have clicked off it.


1 Answers

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},
like image 130
Jared Forsyth Avatar answered Oct 20 '22 09:10

Jared Forsyth