Search

onClick event Handling in React with Example

post-title

In this tutorial, we are going to look at how to handle React onClick events. Event handlers help in making the decision which action should be taken when an event is fired. In an application, a user might click, hover, scroll, or insert any value in an input field.

Handling events in React is simple; events are declared in camelCase in a React app. For instance, if you have to define the onclick event, so we take a little different approach and declare onClick event this way in a React application.

React is a popular front-end framework, and it does follow the best practices to make it works hard to make it popular among web developers around the globe. React follows a synthetic event approach to enhance the consistency and best performance in React web and mobile applications.

The Synthetic Events offer flexibility by making the events 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 browsers.

It delivers high-quality performance by deliberately using the event delegation. Although event handlers are not added in nodes by React. Preferably, a single event listener is connected with the root of the React document. When an event is triggered, then the React add it to the respective component’s element.

React onClick Event Handling Examples

Let’s start learning how to use various onClick Events in React, first we set up a basic React app using using create-react-app.

Install React App

Run following command to install react app.

npx create-react-app react-onclick-events

Get inside the project folder.

cd react-onclick-events

Run command to start the React app.

npm start

Above command will open your app on the following URL: localhost:3000

Click on Button to Call Custom Function

React onClick event handler is very much useful when we required to perform a particular action. It could be achieved by just clicking on a link, button, or even on any specific element in a web page.

Let’s check out some instances of how we can use the onClick event handler in a React app.

We will create React onClick event handling examples in common src/App.js file in this tutorial.

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 above React component, we 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 a user clicks on this button, this button will trigger the helloThere function and show the Hi! Admin message on the screen.

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 is 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 is to remember here is that you must not forget to add the parentheses right after the method name. Check the given below example for 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;

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 pop up and display message in 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;

Get Button Value with Inline onClick Event Handler

In the following example, we passed value in the button and retrieve that value with the help of 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;

Retrieve an Array Using Inline onClick Event in React

In this example, we will learn how to remove the array values using inline onClick event handler. We declared the fruits array and get the array items using map() method and removing those items using 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;

i hope you like this article.