Author avatar

Gaurav Singhal

React Dynamic Events

Gaurav Singhal

  • Apr 22, 2020
  • 6 Min read
  • 439 Views
  • Apr 22, 2020
  • 6 Min read
  • 439 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Events provide a dynamic interface to applications, adding better user interactivity across them. The events in a React app are pretty similar to those used in vanilla JavaScript to manipulate the HTML DOM by attaching various events to the element, so each event with the given element should have an event handler attached.

In this guide, we are going to learn what an event handler is and how to use dynamic event handling in a React application.

Attach Events in React

As you know, React is a JavaScript-based library, which means it supports all the events attached to any of the HTML elements. Because of this, accessing or attaching events is a bit different than in vanilla JavaScript.

In React, there should be an event attached to the event handler in order to process the desired value. It can be attached using the event key as explained below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { Component } from "react";
import { render } from "react-dom";
import Demo from "./Demo";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  testMethod() {
    console.log("Hello World");
  }

  render() {
    return (
      <div>
        <Demo eventKey={this.testMethod} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
jsx

Here in the above example, testMethod () is an event handler and eventKey is used to send the event as a props to the child component. It can be accessed into the child component like this.

1
2
3
componentDidMount() {
    this.props.eventKey()
}  
jsx

From the child component, the event is accessed through this.props, so that is one of the ways to access the event from the parent component.

Handle Dynamic Events with Radio Group Control

So far, you've learned how to attach an event handler to a child component and how to access it from the child component, but sometimes you may need to maintain common events for a group of elements.

In this section, you'll learn how to maintain the common event handler along with the group of radio buttons.

Create a component called DynamicRadioList.jsx and run the following lines of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import React, { Component } from "react";

class DynamicRadioList extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      selectedGender: "Male"
    };
    this.onGenderChange = this.onGenderChange.bind(this);
  }

  onGenderChange(event) {
    this.setState({
      selectedGender: event.target.value
    });
  }

  render() {
    const { items } = this.state;

    return (
      <div>
        <label>
          <input
            type="radio"
            value="Male"
            checked={this.state.selectedGender === "Male"}
            onChange={this.onGenderChange}
          />
          Male
        </label>
        <label>
          <input
            type="radio"
            value="Female"
            checked={this.state.selectedGender === "Female"}
            onChange={this.onGenderChange}
          />
          Female
        </label>
        <label>
          <input
            type="radio"
            value="Other"
            checked={this.state.selectedGender === "Other"}
            onChange={this.onGenderChange}
          />
          Other
        </label>
      </div>
    );
  }
}

export default DynamicRadioList;
jsx

In this example, you have three different radio buttons called Male, Female, and Other.

Along with the radio buttons, you have two important properties:

  • Checked, which is used to determine whether the radio button is checked or not
  • onChange, which looks for changes in terms of selection

As soon as a user changes their selection, an updated value can be updated into the state via a method called onGenderChange().

This is how you can get the appropriate value based on user interactivity using dynamic events along with HTML elements.

Handle Dynamic Events with a Dynamic Array List

A dynamic list of records is found in web applications where users select any one of them to see the details.

In this situation, you need to get the all details regarding the selected record by the user from the list of items, which you can do by maintaining the common dynamic event, which can be useful for getting selected record details.

Create a new component called DynamicList.jsx and run the following lines of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React, { Component } from "react";

class DynamicList extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      items: ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
    };
    this.onItemClick = this.onItemClick.bind(this);
  }

  onItemClick(event) {
    console.log(event.target.innerHTML)
  }

  render() {
    const { items } = this.state;

    return (
      <div>
        <ul>
          {items.map((item, index) => {
            return <li onClick={this.onItemClick} key={index}>{item}</li>;
          })}
        </ul>
      </div>
    );
  }
}

export default DynamicList;
jsx

In the above example, there is one state variable called items, which contains the list of array items to be rendered.

Tthe list of items is mapped into the render() method, but one property to notice is onClick ().

1
2
3
4
5
6
7
8
9
return (
      <div>
        <ul>
          {items.map((item, index) => {
            return <li onClick={this.onItemClick} key={index}>{item}</li>;
          })}
        </ul>
      </div>
    );
jsx

As soon as the user clicks on any of the items from the list, the event handler onItemClick() will get the inner HTML of the HTML for further processing.

There can be a number of items in the list, but the method onItemClick() is common for all of them. You can say it’s a dynamic event that handles all the items' click events.

This is one of the most widely used approaches to get selected values that maintain a single function for multiple elements.

Conclusion

In this guide, we have learned what an event handler is and how to use it in a React app, icluding two examples using a radio group and an array list.

You can create and assign dynamic events to elements or child components based on your particular functional requirements. I hope this guide was helpful to you. Keep reading.

6