Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

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

Capturing and applying logic to an HTML onBlur event allows other UI interactivity. This guide will hook in logic with an onBlur event in a React.js component.

Oct 5, 2020 • 6 Minute Read

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.

      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>
    );
  }
}
    

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:

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

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

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

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:

      <input
  type="text"
  onBlur={this.handleOnBlurUsername.bind(this)}
/>
    

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:

      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.
    

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.

Raphael Alampay

Raphael A.

Raphael Alampay is the co-founder of Cloudband Solutions Co., a software development and consultancy company that caters to custom based software for SME around the globe. Using time and tested technology such as Java, Ruby on Rails, Python, PostgreSQL and Linux, he has a passion for creating applications that solve real world problems making businesses more efficient and innovative at the same time. His craft in software is largely based on the philosophy of "kaizen" which means continuous improvement; that any piece of software is meant to be continuously improved over time. Aside from software development, Raphael also teaches computer science in universities and corporate entities largely in the field of programming and machine learning. He currently holds a master's degree in Computer Science and is working on his PhD in Computer Science as well. If not programming or teaching, Raphael enjoys playing the piano and guitar in his spare time.

More about this author