How to create an event in React ? (original) (raw)

Last Updated : 05 Dec, 2023

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:

**Syntax:

function Component() { doSomething(e){ e.preventDefault(); // Some more response to the event } return ( ); }

**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