Open In App

How to create an event in React ?

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the development of contemporary webpages, user interactions play a pivotal role. These interactions include mouse clicks, keypresses, or even uncommon events like connecting a battery to a charger. As developers, our task is to actively “listen” to these events and subsequently ensure that our application responds appropriately.

Prerequisites:

Approach to create an Event in React:

  • Make sure that React is imported. And also import the ‘App.css’ file as it contains some CSS styles for the app component.
  • Clear everything written inside the <div> with ‘className’ App.
  • Create a heading and a button inside this div.
  • Create an onClick event inside the button and pass the ‘eventHandler’ function inside it. We define the function at the top of the ‘App’ component.
  • Add the alert inside the function so that we can listen to the event and generate an alert whenever the event occurs.

Syntax:

function Component() {
    doSomething(e){
        e.preventDefault();
        // Some more response to the event
    }
    return (
        <button onEvent={doSomething}></button>
    );
}

Steps to Create the React Application And Installing Module:

Step 1: Create a React application using the following command:

npx create-react-app name_of_the_app

Step 2: After creating the react application move to the directory as per your app name using the following command:

cd name_of_the_app

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4",
}

Example: Now write down the following code in the App.js file

Javascript




import React from 'react';
 
function App() {
    function eventHandler() {
        alert('Geeksforgeeks is the best platform to learn coding!');
    }
 
 
    return (
        <div className='App'>
            <h1>Welcome to Geeksforgeeks</h1>
            <button onClick={eventHandler}>Click for alert!</button>
        </div>
    );
}
 
export default App;


Step to run the application: Open the terminal and write the following command in your terminal.

npm start

Output: Open the browser and type the localhost:3000


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads