React provides its own cross-browser-compatible synthetic events that are a wrapper around the native browser events. These events are named using the camelCase convention. We need to pass a handler function to these event props which gets executed when the event is fired. We can pass the handler function to the event prop using the syntax shown below.
Syntax:
const handleClick = () => {
console.log("Hello");
}
<div onClick={handleClick}>Hello</div>
Prerequisites:
Approach:
Using an event in React JS is done by defining a function for that event. This function is called when the corresponding event is triggered and the code is executed.
Steps to Create React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure:
Example: This example implements the defined eventHandler function linked to onClick event. When the click event is triggered it call the handler and shows the click alert on the UI.
// Filename - App.js import "./App.css" ;
const App = () => { const handleClick = () => {
alert( "Hello Geek" );
};
return (
<div className= "container" >
<button className= "btn" onClick={handleClick}>
Press Me
</button>
</div>
);
}; export default App;
|
/* Filename - App.css */ .container { height : 100 vh;
width : 100 vw;
display : flex;
justify- content : center ;
} .btn { align-self: center ;
background-color : rgb ( 47 , 173 , 173 );
font-size : 50px ;
color : white ;
border-radius: 10px ;
border : none ;
} .btn:active { background-color : rgb ( 16 , 88 , 88 );
} |
Step to run the application: Use the following command on the command line to start the application.
npm start
Output: We can use our React app by visiting http://localhost:3000 on the browser.