React onClick Event Handling Methods With Examples

Hi friends. In this tutorial today, we will come to learn how to Handle React onClick Events. Some of us may know already that event handlers help in making the decision of which action should be taken when an event is fired. In a mobile or web app, the user might click, hover, scroll, or insert any value in an input field.

Handling Events in React is not rocket science. It’s quite simple and smooth to learn and then implement. The events are declared in camelCase in a React app. For example, if we need to define the onclick event, then we take a little different approach and declare the onClick event this way in a React app.

Also, React follows a synthetic event approach to enhance the consistency and best performance in React web and mobile apps.

The Synthetic Event offers flexibility by making the vents easy to use due to the reason it has the same properties across all the various platforms and browsers.

The SyntheticEvent is a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all the browsers.

It delivers high-quality performance by using the event delegation. Though the event handlers are not added in Nodes by React. A single event listener is connected with the root of the React document. When an event is triggered, then React adds it to the respective component’s element.

 

Let’s see now what steps we will see in this guide:

  1. Install React App
  2. Click On Button To Call Custom Function
  3. Handle Inline Function With React onClick Event Handler
  4. Manage Multiple Methods With onClick Events In React
  5. Get Button Value With Inline onClick Event Handler
  6. Retrieve An Array Using Inline onClick Event In React

 

Step 1- Install The React App

First of all, we have to set up a new React app by running the below-given command in the terminal:

npx create-react-app react-onclick-events

Net is needed to get inside the project folder:

npm start

 

Step 2- Click On Button To Call Custom Function

React onClick event handler is quite much of use when we need to perform a particular action. It can be achieved by simply clicking on a link, button or any other element on a web page.

See below in which we have created React onClick event handling examples in common in src/App.js file:

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.helloThere = this.helloThere.bind(this);
  }

  helloThere() {
    alert('Hi! Admin');
  }

  render() {
    return (
      <button onClick={this.helloThere}>
        Click Here
    </button>
    );
  }
}

export default App;

 

In the above React component, we have created a simple helloThere() custom function along with a basic button. We added an onClick event with the button and passed the helloThere function in it. Whenever the user clicks on this button, then it will trigger the helloThere function and show the Hi! Admin message on the screen.

 

Step 3- Handle Inline Function With React onClick Event Handler

As the name suggests, an Inline function is a function or method which is declared within the onClick event, it exclusively works when the React component is rendered.

It is created inside the render method due to the function is defined inside the onClick event handler.

It’s a handy way of calling the Inline method, and it is required mainly when you want to pluck the value from the target elements value or a loop may be.

The important thing to remember here is to add the parentheses right after the method name. Check the given below example for a more concise way of writing Inline onClick events in React.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <button onClick={() => alert('Hi! Admin')}>
        Click Here
      </button >
    );
  }
}

export default App;

 

Step 4- Manage Multiple Methods With onClick Events In React

Sometimes, we have to deal with a situation where we have to call multiple functions by just clicking on a single button. Let’s show an alert message in poop up and display a message in the console.

import React, { Component } from 'react';

class App extends Component {

  helloThere() {
    alert('Hi! Admin');
  }

  messageInConsole() {
    console.log("It's working")
  }

  render() {
    return (
      <button onClick={() => {
        this.helloThere();
        this.messageInConsole();
      }}>
        Click me!
      </button>
    );
  }
}

export default App;

 

Similarly, we can also declare the Inline code within the onClick event handler. Let’s display a message in the browser’s console and take the value from a variable.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <button onClick={() => {
        let user = "Admin";
        console.log('Hi, ', user);
      }}>
        Click Here
      </button>
    );
  }
}

export default App;

 

Step 5- Get Button Value With Inline onClick Event Handler

In the below example, we have passed the value in the button and retrieve that value with the help of the inline onClick event handler.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <button value="John Doe" onClick={event => alert(event.target.value)}>
        Click Here
      </button>
    );
  }
}

export default App;

Step 5- Retrieve An Array Using Inline onClick Event In React

In this example, we will learn how to remove the array values using an inline onClick event handler. We declared the fruits array and get the array items using the map() method and removing those items using the inline onClick event handler.

import React, { Component } from 'react';

class App extends Component {

  fruits = ['Apple', 'Mengo', 'Orange', 'Banana', 'Cherry', 'Kiwi'];

  removeFruit(fruits) {
    alert(fruits)
  }

  render() {
    return (
      <ul>
        {this.fruits.map((item) => (
          <li>
            <button onClick={() => this.removeFruit(item)}>
              Click Here
            </button>
          </li>
        ))}
      </ul>
    );
  }
}

export default App;

 

Summary

So, here we reach the end of this tutorial. In this guide, we have completely learned how to implement React onClick Event Handling with examples. Hope you have well understood the concept and manner to complete the task.

 

Thanks

 

Leave a Reply

Your email address will not be published. Required fields are marked *