Author avatar

Raphael Alampay

Client-side Checking with React.js JSX Events Using onBlur

Raphael Alampay

  • Oct 5, 2020
  • 6 Min read
  • 64 Views
  • Oct 5, 2020
  • 6 Min read
  • 64 Views
Web Development
Front End Web Development
Client-side Frameworks
React

Introduction

One common event in HTML is onBlur, wherein an input element loses focus as it is passed to another element. This is often done when the user hits tab or simply clicks the next input element. Capturing this event and applying logic to it allows other UI interactivity, such as validation of user input as focus is released. This way the user won't have to wait to submit the input before finding out what went wrong. This simple example will demonstrate how to hook in logic with the onBlur event in the context of a React.js component.

Setup

Suppose you have a login form that accepts a username and password in the form of a React.js component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React from 'react';

export default class LoginForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: "",
      messageUsername: "",
      messagePassword: ""
    }
  }

  render() {
    return (
      <div>
        <label>
          Username:
        </label>
        <input
          type="text"
        />
        {this.state.messageUsername}
        <br/>
        <label>
          Password:
        </label>
        <input
          type="password"
        />
        {this.state.messagePassword}
        <hr/>
        <button>
          Login
        </button>
      </div>
    );
  }
}
javascript

The following state values are maintained in this component:

  • username: The variable to hold the username that the user would enter
  • password: The variable to hold the password that the user would enter
  • messageUsername: Message to be displayed after user loses focus from username input and some condition is passed to invoke a notification relating to the username.
  • messagePassword: Message to be displayed after user loses focus from password input and some condition is passed to invoke a notification relating to the password.

Event Handlers

You should have an event handler function that will be triggered in the event of an onBlur. To do this, first define the needed function:

1
2
3
4
5
6
7
8
9
10
11
12
13
handleOnBlurUsername(event) {
  var username        = event.target.value;
  var messageUsername = "";

  if(!username) {
    messageUsername = "Username required"; 
  }

  this.setState({
    username: username,
    messageUsername: messageUsername
  });
}
javascript

The logic of the function is pretty simple. First, it gets the username of the input by accessing it from event.target.value. Next, it sets a blank value for a temporary messageUsername variable. You apply a simple rule that checks if username has a value. If not, then fill in a value of "Username required" for messageUsername. The function ends by updating the state of username and messageUsername for this component.

Binding to `onBlur`

Given your event handler, attach the function to the input element for the username like so:

1
2
3
4
<input
  type="text"
  onBlur={this.handleOnBlurUsername.bind(this)}
/>
jsx

Make sure that you call .bind(this) after the function in order to retain this to point to the instance of the component.

Now that the function is attached to the input, if a user leaves or releases focus from the input element for username and nothing was put in, messageUsername will be set with a message which in turn will appear below the input element, thus notifying the user that they need to input a username.

Overall Code

The overall code should look like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React from 'react';

export default class LoginForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: "",
      messageUsername: "",
      messagePassword: ""
    }
  }

  handleOnBlurUsername(event) {
    var username        = event.target.value;
    var messageUsername = "";

    if(!username) {
      messageUsername = "Username required"; 
    }

    this.setState({
      username: username,
      messageUsername: messageUsername
    });
  }

  render() {
    return (
      <div>
        <label>
          Username:
        </label>
        <input
          type="text"
          onBlur={this.handleOnBlurUsername.bind(this)}
        />
        {this.state.messageUsername}
        <br/>
        <label>
          Password:
        </label>
        <input
          type="password"
        />
        {this.state.messagePassword}
        <hr/>
        <button>
          Login
        </button>
      </div>
    );
  }
}

Test it out by first clicking the username input element and then immediately pressing tab or clicking the password input element to release focus from the username input. The message should then appear after the focus is released if nothing was put in.
javascript

Conclusion

There are many events in HTML that allow you to attach event handlers to add additional logic and create a more interactive experience with the user. 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.setState.

If you notice the code, only username handling was implemented. As additional practice, try the same approach discussed in this guide to attach an event handler to onBlur for the password section of the component. Try to add additional rules to change the message that appears below each input element if that rule is invoked.

2