Event Handling In React
we use the concept of virtual DOM, so all the events need to specify at the time of creating the component. Here in App.js file, we have defined one component App, which is having a button. We have used “onClick” event and we are providing a method name instead of a string. As in JSX, we specify javascript in “{ }” that is why the method name is in the { }.
You can create React app using the following command and move to the project directory:
npx create-react-app nameoftheapp
cd nameoftheapp
Project Structure:
Example: This example demonstrate the use of event handlers in React JS.
Javascript
// Filename - App.js import React from "react" ; export default function App() { const greet = () => { window.alert( "onClick in React sent me" ); }; return ( <div> <button className= "btn" onClick={greet}> Greet me using onClick React </button> </div> ); } |
Step to Run the Application: You can run your app using the following command in the terminal inside project directory.
npm start
Output: This output will be visible on http://localhost:3000/ on the browser window.
- In HTML, we specify event in html tags like onclick, onsubmit etc. and pass the string that contain the parenthesis at the end.
- In html, we can also add them afterword using external javascript using addEventListener.
- In React, we specify event at the time of creating our component.
- we use camel case convention in React i. e. onClick, onSubmit.
- In React, we bind them using method name only like onClick={greet}.
- addEventListener cannot be used in React component.
Difference between HTML and React Event Handling
Event handling in HTML and React are different from one another in terms of syntax and some rules. The reason behind this is that React works on the concept of virtual DOM, on the other hand, the HTML has access to the Real DOM all the time. We are going to see how we can add the events in HTML and how React differs in event handling.
Contact Us