Wednesday, November 20, 2024
Google search engine
HomeLanguagesGive an example of using Events

Give an example of using Events

React is a Javascript front-end library that is used to build single-page applications (SPA). 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.

const handleClick = () => {
    console.log("Hello");
}
<div onClick={handleClick}>Hello</div>

In this article, we are going to discuss a simple example of using events in React.

Creating 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: The project structure will look like the following.

Approach: Now in this project, we have created a button on which we have an onClick prop. We have assigned a handler function to this onClick prop. When we click this button, our handler function is executed and shows an alert window. Now to follow along you can write the following codes in your App.js and App.css file.

Below is the implementation of the above approach.

Filename: App.js

Javascript




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

CSS




.container {
  height: 100vh;
  width: 100vw;
  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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments