ReactJS Input onBlur event example


In this post, You are going to learn Input blur event handlerin react application application and Simple example input blur event uses.

Reactjs provides an onBlur event bounded to Input elements on userform, onBlur is an javascript blur event, can attach callback handler to this, called when input lost focus.

Syntax

<input onBlur="eventHandler">

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

eventHandler= event => {

}

onBlur event in Reactjs can be used in following cases

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

Other versions available:

React application from scratch

create-react-app command creates new applications with all files and build pipeline. It provides all latest reactjs and its 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 project structure, install depedencies to start running.

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

cd react-input-blur
npm start
react-google-fonts@0.1.0 start B:\blog\jswork\react-google-fonts
react-scripts start
Compiled successfully!

You can now view react-google-fonts in the browser.

  Local:            http://localhost:3002

React application running with localhost:3002

onBlur Event in react application example

Following is an example for for displaying entered value after input focus is lost

  • Create a react component by extending Component class
  • In Render function, Input is defined with name with onBlur event bound to callback handler onBlurEvent
  • onBlurEvent has a method with event which 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 ecuted, onBlurEvent function got the value using event.target.value, and updating the state with this value using setState({name:value}) method.
  • In render function, retrieve the name from state object and displayed 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;

Blur Event validation in React application

Another important thing with blur event is enabling validation at input element. Following is an example for input empty check validation on focus left from element. In this example, regular expression patter to 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;

Submit form with onblur Event examples

Sometimes, We want user to submit form on blur event. with this, Validation errors 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 avialable 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

On this tutorial, Basic onBlur event in react application

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

Finally, onBlur events are useful for handling form validations and helps simplifying the handling user forms easier.

Similar Posts