React JS DOM Event Handling Tutorial with Examples: onClick, onChange

React event handling tutorial; In this React guide, we will explain how you can handle onClick similarly onChange events through React event handlers to perform certain actions.

Event handlers is the common term that is heard a lot in application development. Theoretically, it is a process mainly related to activities being done within the DOM (document object model) or web page. For instance:

  • Clicking on a button
  • On value change (File upload, Select value from dropdown etc.)
  • On the web page scroll
  • Clicking on keyboard buttons
  • Loading a web page
  • Typing on the input fields
  • Hovering over the web page

If you come from an HTML background, you must be aware of DOM events; fundamentally, HTML DOM lets JavaScript act, in conjunction with HTML events. Essentially, JavaScript does the job for you by invoking the custom functions related to a specific event triggered.

Here is the common events provided by JavaScript: onchange, onclick, onmouseover, onmouseout, onkeydown and onload. Although event handlers in React Js almost identical to the HTML events, all the before mentioned events also exist in React framework; handling events in React is exorbitantly facile, likewise similar to handle events on DOM elements.

Nevertheless, they work the same; however, adding event hander in the React web page is different from regular HTML DOM; in React, events are declared using the camelCase approach instead of lowercase. Plus, JSX only allows a function as the event handler instead of a string.

How to Handle onClick and onChange Events in React

  • Step 1: Create React Project
  • Step 2: Invoke Custom Function with onClick Event
  • Step 3: React onClick Inline Event Example
  • Step 4: React onClick Trigger Multiple Functions
  • Step 5: Get Button Value onClick Event
  • Step 6: React onChange Event Handler Example
  • Step 7: Start React Project

Create React Project

We assume you have set up the React app for this demo; however, if not, then you may use the given below command to create a new React application.

npx create-react-app user-management-app

Move to project’s root.

cd user-management-app

Invoke Custom Function with onClick Event

Here is the simple on click event, which calls the custom function, which basically shows the users list in an alert popover box. On click event in React works cross-browser and doesn’t deteriorate in modern browsers.

import React, { Component } from "react";

export default class EventHandlers extends Component {

    constructor(props) {
        super(props);
        this.showUsers = this.showUsers.bind(this);
      }
    
      showUsers() {
        alert('John, Henry, Matt, Tony, Kelly');
      }
    
      render() {
        return (
          <button onClick={this.showUsers}>
            Click
        </button>
        );
      }
            
}

React onClick Inline Event Example

The previous example described how to call the function when the user clicks on the button; now, this example will show you how to define the custom function inline and bind it with the onClick() event handler.

import React, { Component } from 'react';

class App extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
        <button onClick={() => alert('Apples, Apricots, Bananas')}>
            Click
        </button >
        );
    }

}

export default App;

React onClick Trigger Multiple Functions

React is not an ordinary frontend framework; rather, it offers a profound development environment for rapid application development. Not just a single function, but you can also call multiple functions using the react on click event handler.

The following code snippet shows you calling multiple functions after clicked on the button the button; the two functions will be triggered respectively.

import React, { Component } from 'react';

class App extends Component {

    constructor(props) {
        super(props);
    }

    showUsers() {
       alert('John, Henry, Matt, Tony, Kelly');
    }
    
    alertMsg() {
       alert("User list is loading ...")
    }
    
      render() {
        return (
          <button onClick={() => {
            this.showUsers();
            this.alertMsg();
          }}>
            Trigger Multiple Events
          </button>
        );
      }

}

export default App;

Get Button Value onClick Event

The event object allows you to get the button value and other important aspects necessary to take a pragmatic approach for building an app.

The onClick event handler returns the event, denoted by e in the given an example, and we showed how to access the button value with inline on click event.

import React, { Component } from 'react';

class App extends Component {

    constructor(props) {
        super(props);
    }
    
    render() {
        return (
            <button value="The Eternals" onClick={e => console.log(e.target.value)}>
                Click
            </button>
        );
    }

}

export default App;

React onChange Event Handler Example

We have explored all the primordial on click events; let us move forward and check how to handle onChange event in React. Let us test out React on change events using a select dropdown element, create a function, set the state and update the dropdown value when the user changes the select dropdown value.

import React, { Component } from 'react';

class App extends Component {

    constructor(props) {
        super(props)

        this.state = {
          value: ''
        }
      }

      onDropdownChange (e) {
        alert(e.target.value)
      }

      render () {
        return (
            <div>
                <select 
                    value={this.state.selectValue} 
                    onChange={this.onDropdownChange}>
                        <option value="Mangoes">Mangoes</option>
                        <option value="Oranges">Oranges</option>
                        <option value="Watermelons">Watermelons</option>
                </select>
            </div>
        )
      }

}

export default App;

Start React Project

In the last step, you need to open the command prompt and start typing the command thereafter, execute the command to run the application.

npm start

You can check out what we have built so far just by using the following url.

http://localhost:3000

Conclusion

The react event handling tutorial is over; however, this is not done entirely because we have touched very few event handlers.

Nonetheless, there are plenty of event handlers that you may require for the react application development. Although react onClick event, react onChange events are good to start with and used more than often.