How to Handle Events in React App

Published on July 17, 2020 2 min read

In this article, we’re going to see how to handle events in React application. React events are named using camelCase, rather than lowercase. React elements are able to fire all the same events as the usual DOM elements.

Table of Contents

  1. Example
  2. Functional Components
  3. Inline Function
  4. Class-Based Components
  5. More Examples

Example

Before going to start, let’s take a look at an example. In HTML:

<button onclick="activateLasers()">
  Activate Lasers
</button>

In React, it is slightly different:

<button onClick={activateLasers}>
  Activate Lasers
</button>

Functional Components

To prevent the default link behavior of opening a new page, you can write:

<a href="#" onclick="console.log('The link was clicked.'); return false">
  Click me
</a>

In React, this could instead be:

App.js
import React from 'react';

function App() {

  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

export default App;

✅ Correct syntax:

<button onClick={functionName}>
  Action!
</button>

❌ Wrong syntax:

<button onClick={functionName()}>
  Action!
</button>

We’re able to pass arguments:

App.js
import React from 'react';

function App() {

  function handleClick(name) {
    console.log(name);
  }

  return (
      <button onClick={()=>handleClick('Obydul')}>
        Click me
      </button>
  );
}

export default App;

Inline Function

Inline function is defined inside of the onClick handler. Let’s take a look at an example:

App.js
import React from 'react';

function App() {
  return (
    <button onClick={() => alert('clicked'))}>
      Click me!
    </button>
  );
}

export default App;

Pass value to inline function:

App.js
import React from 'react';

function App() {
  return (
    <button value="hello!" onClick={e => alert(e.target.value)}>
      Click me!
    </button>
  );
}

export default App;

Class-Based Components

The class components make use of ES6 class and extend the Component class in React. Sometimes called stateful components as they tend to implement logic and state. Have a look at an example:

Counter.js
import React, { Component } from 'react';

class Counter extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      num : 0
    }
  }

  render(){
    return (
        <div>
        <h1>Counter</h1>
        <h3>{this.state.num}</h3>
        <button onClick={() => this.setState({ num : this.state.num + 1})}>
          Increment
        </button>
      </div>
    )
  }
}

export default Counter;

More Examples

Example 1: Let’s pass value from an array to an inline function:

Components/Users.js
import React from 'react';

function Users() {

  const users = [
    {id: 1, name: 'Name 1'},
    {id: 2, name: 'Name 2'},
    {id: 3, name: 'Name 3'},
    {id: 4, name: 'Name 4'},
    {id: 5, name: 'Name 5'},
  ];
  
  function userAction(id) {
    console.log(id);
  }
  
  return (
    <ul>
      {users.map(user => (
        <li>
          <button onClick={() => userAction(user.id)}>{user.name}</button>
        </li>
      ))}
    </ul>
  );
}

export default Users;

Now import the Users component to App.js & see the output:

App.js
import React from 'react';
import Users from './Components/Users';

function App() {
  return (
    <div className="App">
      <Users/>
    </div>
  );
}

export default App;

Example 2: We can handle many events at once. Here’s the example of handling 2 events at once:

Todo.js
import React, { Component } from 'react';

class Todo extends React.Component {

  handleClick = () => {
    console.log('clicked');
  }
  handleInput = (e) => {
    console.log(e.target.value);
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          ADD
        </button>
        <input onChange={this.handleInput}/>
      </div>
    );
  }
}

export default Todo;
That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

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