React Dynamic Events
Apr 22, 2020 • 6 Minute Read
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.
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"));
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.
componentDidMount() {
this.props.eventKey()
}
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.
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;
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.
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;
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 ().
return (
<div>
<ul>
{items.map((item, index) => {
return <li onClick={this.onItemClick} key={index}>{item}</li>;
})}
</ul>
</div>
);
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.