ReactJS Input onBlur event example

In this post, Learn Input blur event handler in react application application and Simple example input blur event uses.

Reactjs provides an onBlur event bound to Input elements on the user form. onBlur is a javascript blur event, can attach a callback handler to this, called when input lost focus.

Syntax

<input onBlur="eventHandler" />

onBlur is bounded to an input element with an event handler, Event handler is a function in a component, executed when input focus is lost.

eventHandler = (event) => {};

onBlur event in Reactjs can be used in the following cases

  • storing the value from the form input - one-way binding
  • Validation of input fields.

Other versions available:

Create React application from scratch

The create-react-app command creates new applications with all files and builds pipelines. It provides all the latest reactjs and their dependencies.

npx create-react-app react-input-blur

Success! Created react-input-blur at B:\blog\jswork\react-input-blur
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    , and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-input-blur
  yarn start

Created react application react-input-blur, with the project structure, and install dependencies, and started running the application.

Go to the application root folder, start the server using npm start

cd react-input-blur
npm start
[email protected] start B:\blog\jswork\react-input-blur
react-scripts start
Compiled successfully!

You can now view react-input-blur in the browser.

  Local:            http://localhost:3002

React application running with localhost:3002

react onBlur input Event example

The following is an example of displaying entered value after input focus is lost.

  • Create a react component by extending the Component class
  • In the Render function, Input is defined with name with onBlur event bound to callback handler onBlurEvent.
  • onBlurEvent has a method with an event that holds current input element data.
  • In Constructor, initialized props object and created a state object with default form values
  • In-State object, form name is initialized with empty values initially
  • During input focus lost ie user typed and moved the focus from input box, blur event is ex executed, onBlurEvent function got the value using event.target.value, and updating the state with this value using setState({name:value}) method.
  • In the render function, retrieve the name from the state object and display it to the user.
import React, { Component } from "react";

class InputBlurComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
  }

  onBlurEvent = (event) => {
    const { value } = event.target;
    this.setState({ name: value });
  };

  render() {
    const { name } = this.state;
    return (
      <div>
        <input
          type="text"
          name="name"
          placeholder="Enter a name"
          onBlur={this.onBlurEvent}
        />
        {name}
      </div>
    );
  }
}
export default InputBlurComponent;

How to add input blur validation in React application

Another important thing with the blur event is enabling validation at the input element. Following is an example for input empty check validation on focus left from the element. In this example, regular expression patterns handle input inline validations.

import React, { Component } from "react";

class InputBlurComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      isValid: true,
    };
  }
  onBlurEvent = (event) => {
    const { value } = event.target;
    const urlRegEx = /^\s+$|^$/gi;
    let isValid = urlRegEx.test(event.target.value);
    isValid = !value;
    this.setState({
      name: value,
      isValid,
    });

    console.log("result ", isValid);

    return isValid;
  };

  submitForm = () => {
    const { name } = this.state;
    console.log("entered name", name);
  };

  render() {
    const { isValid, name } = this.state;
    return (
      <div className="App">
        <form>
          <input
            type="text"
            name="name"
            placeholder="Enter a name"
            onBlur={this.onBlurEvent}
            onChange={this.onChange}
          />
          {isValid && <div style={{ color: "red" }}>Name is required</div>}
          <br></br>
          <button onClick={this.submitForm} disabled={!isValid}>
            Submit
          </button>
        </form>
      </div>
    );
  }
}
export default InputBlurComponent;

How to Submit input form with onblur Event in React

Sometimes, We want the user to submit the form on blur event. with this, Validation errors are shown to form on submitting the form.

  • `React refs’ provides triggering some actions on form.
  • Created refs using React.createRef in the component constructor, so that it is available across react component life cycle
  • Bind created ref in the form using refattribute ref={this.myRef}
  • onBlur event handler, refrs are accessed using this.myRef.current, returns form
  • submit the form using this.myRef.current.submit()
import React, { Component } from "react";

class InputBlurComponent extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  submitNameForm = (event) => {
    const { value } = event.target;
    this.myRef.current.submit();
  };

  render() {
    return (
      <form ref={this.myRef}>
        <input type="name" onBlur={this.submitNameForm} />
      </form>
    );
  }
}

export default InputBlurComponent;

Conclusion

In this tutorial, Basic onBlur event in react application

  • Example basic onBlur event to store input data
  • Input form validation
  • Submit user form using the onBlur event

Finally, onBlur events are useful for handling form validations and help simplify the handling of user forms easier.