Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The event handler determines what to do whenever an event is triggered. The event could be a button click, a keyboard keypress, or a hovering mouse cursor.
Handling events in react is very crucial because changes made on event helps the user to interact with our application.
Handling events in react is very much similar to how we handle events in DOM elements. If you are familiar with handling events in javascript, then handling events in react would be a cakewalk for you.
But before starting with handling events in react, let,s first understand what is an event.
An event is an action that is fired as a result of user actions or the action taken by the system. For example, clicking a mouse button, loading a web page, pressing a key, window resizing, and other interactions are called events.
React has its own system for handling events which is quite similar to how we handle events in DOM elements.
Now we will look at important rules to follow while creating events in React.
camelCase Convention: Instead of using lowercase for naming, we use camelCase while giving names of the react events. That simply means we write ‘onClick’ instead of ‘onclick’.
Pass the event as a function: In React, we pass a function enclosed by curly brackets as the event listener or event handler, unlike HTML, where we pass the event handler or event listener as a string.
Prevent the default: Unlike javascript, returning false inside the JSX element does not prevent the default behavior in react. Instead, we have to call the ‘preventDefault’ method directly inside the event handler function
function fun(){
doSomething(e){
e.preventDefault();
// Some more response to the event
}
return (
<button onEvent={doSomething}></button>
);
}
You can also try this code with Online Javascript Compiler
Here, e is a synthetic event. React defines these synthetic events according to the W3C spec. A synthetic event is an object made with a wrapper around the actual event of the browser. This object is cross-browser.
To further enhance your knowledge and gain hands-on experience, you can also consider enrolling in our React Js Course.
Let’s implement a program for event handling in react for our better understanding .we will discuss the program from scratch and in-depth to better understand handling events.
Handling events in react
To create the program for handling event in react, we will firstly create a react application. We will create an app using create-react-app. If you want to learn how to create a react app, you can read out this article.
Steps to create the react app:
Create the app using the following command on your command line:
npx create-react-app event_handling
2. Now after creating the app change the working directory to folder of your project using the following command.
cd event_handling
Now we have successfully created the app now we can start working on the app.
You will see the following folder structure
In your index.js file write the following code to create a onclick event handler that gives an alert on button click.
import React from 'react';
import ReactDom from 'react-dom';
function App() {
function eventHandler(){
alert('Welcome to Coding Ninjas');
}
return (
<div className='App'>
<h1>Welcome to Coding Ninjas</h1>
<button onClick={eventHandler}>Click me</button>
</div>
);
}
ReactDom.render(<App />, document.getElementById('root'));
You can also try this code with Online Javascript Compiler
Once you click on the button the alert is displayed
So we successfully created an app to handle events in react and also learned about event handling in detail with syntax.But what will happen if we are using a class component.
Let’s discuss event handling in class components in detail.
Handling events in class component
Handling events in class components is similar to handling events in functional components.
Let's create an onclick event handler as we created above to understand it better.
If you have noticed we are using this keyword in the above keyword while calling the function this is because in JavaScript, class methods are not bound by default. If you forget to bind this.eventHandler and pass it to onClick, this will be undefined when the function is actually called
2. In the above example we declared the function outside the render but we can also declare it directly in the onclick attribute like this
importReactfrom'react';
importReactDomfrom'react-dom';
classAppextendsReact.Component {
render() {
return (
<divclassName='App'>
<h1>Welcome to Coding Ninjas</h1>
<buttononClick={()=>alert('Welcome to Coding Ninjas')}>Click me</button>
Let’s say that you want to customize the message displayed on clicking the button , you want to display the name of the user. You want to change it for every user so you need a way to pass arguments to event handlers.
React allows us to pass arguments in the event handler. So let’s take a look at how you would pass arguments while handling events in react.
In the above code the alert would be displayed with the name that is passed as an argument to the event handler.
Frequently asked questions
What are the events in react? An event is an action that is fired as a result of user actions or the action taken by the system. For example, clicking the mouse button, loading of a web page, pressing a key, window resizing, and other interactions are called events.
What is an onClick() event? onClick() event occurs when a user clicks on something. It helps the developer to execute a piece of code when a user clicks on the specified objects.
How to pass arguments to an event in react? There are two ways to pass arguments via the Arrow function and the Bind method.
This blog covered the basic concepts of handling events with React, creating the application for handling events and discussed the syntax and program in detail.
If you are preparing for your DSA interviews then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and give you an overview of student interview experience in various product-based companies.