Introduction
Handling events with React elements is very similar to handling events on DOM elements. However, there are a few differences. React events are named using camelCase, and we write React event handlers inside curly braces. In React (JSX), rather than passing a string, we pass a function as the event handler. This chapter will cover these differences, different ways to bind events, the recommended approach, and how to pass parameters to event handlers.
Table of Contents
- Differences in Event Handling
- Handling Events in Class Components
- Example: Handling Click Events
- Handling Events in Functional Components
- Example: Handling Input Change Events
- Different Ways to Bind Events
- Binding in Constructor
- Arrow Functions
- Passing Parameters to Event Handlers
- Example: Passing Parameters
- Key Features of Event Handling
- Conclusion
Differences in Event Handling
React vs. DOM Event Handling
-
CamelCase Naming: React events are named using camelCase, whereas DOM events are named using lowercase.
// React <button onClick={handleClick}>Click Me</button> // DOM <button onclick="handleClick()">Click Me</button> -
Curly Braces for Event Handlers: In React, event handlers are written inside curly braces.
// React <button onClick={handleClick}>Click Me</button> // DOM <button onclick="handleClick()">Click Me</button> -
Function as Event Handler: In React, we pass a function as the event handler instead of a string.
// React <button onClick={handleClick}>Click Me</button> // DOM <button onclick="handleClick()">Click Me</button>
Handling Events in Class Components
Example: Handling Click Events
-
Create a New File for the Component: In the
srcdirectory, create a new file namedButtonClick.js. -
Define the Component: Add the following code to
ButtonClick.jsto create a class component that handles click events:// ButtonClick.js import React, { Component } from 'react'; class ButtonClick extends Component { constructor(props) { super(props); this.state = { message: "Hello, World!" }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ message: "Button Clicked!" }); } render() { return ( <div> <h1>{this.state.message}</h1> <button onClick={this.handleClick}>Click Me</button> </div> ); } } export default ButtonClick;In this example, the
ButtonClickcomponent has a state with amessageproperty. ThehandleClickmethod updates the message when the button is clicked. The event handler is bound to the component instance in the constructor. -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theButtonClickcomponent:// App.js import React from 'react'; import ButtonClick from './ButtonClick'; function App() { return ( <div> <ButtonClick /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a button, and clicking it will change the message.
Handling Events in Functional Components
Example: Handling Input Change Events
-
Create a New File for the Component: In the
srcdirectory, create a new file namedInputChange.js. -
Define the Component: Add the following code to
InputChange.jsto create a functional component that handles input change events:// InputChange.js import React, { useState } from 'react'; function InputChange() { const [inputValue, setInputValue] = useState(""); const handleChange = (event) => { setInputValue(event.target.value); }; return ( <div> <h1>Input Change Event</h1> <input type="text" value={inputValue} onChange={handleChange} /> <p>Current Value: {inputValue}</p> </div> ); } export default InputChange;In this example, the
InputChangecomponent uses theuseStatehook to manage theinputValuestate. ThehandleChangefunction updates the state with the current value of the input field. -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theInputChangecomponent:// App.js import React from 'react'; import InputChange from './InputChange'; function App() { return ( <div> <InputChange /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see an input field, and typing in it will display the current value below the field.
Different Ways to Bind Events
Binding in Constructor
The most common way to bind event handlers in class components is to bind them in the constructor.
// ButtonClick.js
import React, { Component } from 'react';
class ButtonClick extends Component {
constructor(props) {
super(props);
this.state = {
message: "Hello, World!"
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({ message: "Button Clicked!" });
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default ButtonClick;
Arrow Functions
Another way to bind event handlers is to use arrow functions, which automatically bind the this context.
// ButtonClick.js
import React, { Component } from 'react';
class ButtonClick extends Component {
state = {
message: "Hello, World!"
};
handleClick = () => {
this.setState({ message: "Button Clicked!" });
};
render() {
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}
export default ButtonClick;
Recommended Approach
The recommended approach is to use arrow functions for event handlers. Arrow functions are more concise and automatically bind the this context, reducing the risk of errors.
Passing Parameters to Event Handlers
To pass parameters to event handlers, you can use an arrow function or the bind method.
Example: Passing Parameters
-
Create a New File for the Component: In the
srcdirectory, create a new file namedButtonClickParams.js. -
Define the Component: Add the following code to
ButtonClickParams.jsto create a class component that handles click events with parameters:// ButtonClickParams.js import React, { Component } from 'react'; class ButtonClickParams extends Component { handleClick = (name) => { alert(`Hello, ${name}!`); }; render() { return ( <div> <button onClick={() => this.handleClick("Ramesh")}>Click Me</button> </div> ); } } export default ButtonClickParams;In this example, the
ButtonClickParamscomponent uses an arrow function to pass a parameter (name) to thehandleClickmethod. -
Use the Component in
App.js: Opensrc/App.jsand modify theAppcomponent to use theButtonClickParamscomponent:// App.js import React from 'react'; import ButtonClickParams from './ButtonClickParams'; function App() { return ( <div> <ButtonClickParams /> </div> ); } export default App; -
Save and View Changes: Save the files and go to your browser. You should see a button, and clicking it will show an alert with the parameter.
Key Features of Event Handling
- CamelCase Naming: React event handlers use camelCase naming, e.g.,
onClick. - Curly Braces for Event Handlers: Event handlers are written inside curly braces.
- Function as Event Handler: Event handlers are passed as functions, not strings.
- Synthetic Events: Ensures consistent event behavior across different browsers.
- Event Binding: In class components, event handlers need to be bound to the component instance.
- Consistent API: The event handling API in React is consistent with the DOM’s event handling API, making it easy to learn and use.
Conclusion
In this chapter, you learned how to handle events in React, both in class components and functional components. You also learned about the differences between React and DOM event handling, different ways to bind events, and how to pass parameters to event handlers. Event handling is essential for creating interactive UIs in React. In the next chapter, we will explore Conditional Rendering in React.