Hello React Friends,
I will explain event handling in ReactJS in detail in this tutorial guide.
Event handling allows users to interact with a web page and perform actions when events like click or hovering occur. Following are some events that are triggered by the system:
Contents
React event handling is similar to event handling on DOM elements. There are some syntax differences in event handling for React and HTML.
React events are written in camelcase instead of lowercase.
onClick instead of onclick.
React event handlers are passed as a function instead of a string. They are written inside curly braces.
onClick={fireme} instead of onClick=“fireme()”.
Event handling example in React:
<button onClick={fireme}>Click to fire me</button>
Event handling example in HTML:
<button >Example:
import React from 'react'; import ReactDOM from 'react-dom/client'; function MyFireArea() { const fireme = () => { alert(“I am Burn!”); } return ( <button onClick={fireme}>Click to fire me</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<MyFireArea />);Passing Arguments to Event Handlers
Pass an argument to an event handler using an arrow function.
Example:
function MyFireArea() { const fireme = (myArg) => { alert(myArg); } return ( <button onClick={() => fireme(“I am Burned”)}>Click to fire me</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<MyFireArea />);React Event Object
Event handlers have access to the react event that triggered the function.
Example:
function MyFireArea() { const fireme = (myArg, b) => { alert(b.type); /* 'b' represents the React event that triggered the function, in this case the 'click' event */ } return ( <button onClick={(event) => fireme("I am Burned", event)}>Take the shot!</button> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<MyFireArea />);Conclusion:
Event handling in React is the same as handling events in HTML. There are just some differences in syntax between the two. I hope the above example helped you to understand event handling in ReactJS.
Find more blogs on ReactJS – Click here!
Share the tutorial with your friends and stay in touch with us.
Happy Coding!
Click to rate this post![Total: 2 Average: 5]
In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…
In the world of business, understanding financial metrics is crucial for making informed decisions and…
Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…
In this era, businesses are always on the lookout for ways to engage with their…
Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…
E-commerce has transformed the way consumers shop for products and services and interact with businesses.…