image
author

Kela Casey

Software Engineer

Events can be handled in React quite similar to the way we do in HTML, these events be like click, change, mouseover, etc. But ‘React events’ are written in camelCase syntax.

For example: “onClick”instead of “onclick” and the function which this event point to would be written in curly braces, for example: onClick={function}.

In this blog, we will talk only about ‘onClick‘ event handling. The onClick handler allows you to call a function and perform an action when an element is clicked.

Let’s learn about this with an example

Create a new project by the following command:

npm create-react-app reactOnClick

where, reactOnClick is the project name.

Now, go to the project directory and start it-

cdreactOnClick

npm start

You should have your project started in the localhost.

Now, in src/App.js, add the following code:

import React from 'react';
function App() {
const testClick = () => {
alert('Hey, you just clicked me');
};
return (
<div className="App">
<button onClick={testClick}>
Click me!
</button>
</div>
);
}
export default App;

In this, we have a button which when clicked calls the function “testClick” ,which alerts the user that he clicked the button.

You will see something like the following after clicking the button

Some common mistake people do is that they pass the function to the handler with parentheses like:

<button onClick={testClick()}>

what it would do is, call the “testClick” function on every render without even clicking it.

It is not necessary to call a function with a name, we can also call inline functions just like:

<button onClick={() => alert('Hey, you just clicked me')}>

So now you must be thinking, if we cannot pass the function name with parentheses then how can we pass arguments to a function.

It can be easily done with an inline function calling that function.

To be more clear, see the following code:

function App() {
const testClick = (name) => {
alert('Hello ' + name);
};
return (
<div className="App">
<button onClick={() => testClick('John')}>
Click me!
</button>
</div>
);
}

You will see the following in your browser:

Similarly, the states can be managed by ‘onClick’ events-

import React, {useState} from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1>Button is clicked {count} times</h1>
<button onClick={() => setCount(prevState =>
prevState + 1)}>
Click me!
</button>
</div>
};
}
export default App;

And in the browser, we have-

So, Event handlers determine what action should be taken when an event occurs. The “onClick” event is used to listen for click events “onDOM” elements.

Hope you all have a clear picture about ‘onClick’ event handling. Will be sharing more such concepts in my future posts.

How React handle events?

React handle events very similar to how HTML handle events but it uses camelCase syntax unlike HTML and the function which is being called is in the braces instead of a string.

Can you have Two onClick Events?

Yes, we can have multiple onClick events. It can be easily achieved by writing your logic in different functions and call them via other function in the onClick handler

What is preventDefault() in React?

The preventDefault() method cancels the default action of an event. For example, the “submit” button in a form refresh the page on default which can be stopped by preventDefault().

What is Meant by Event Handling?

Event handling is nothing but a mechanism to control what should happen to the component when certain events like click, mouseover, scroll, etc. is occurred in the DOM.

How useful was this post?

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Please do Rate Us and Share!

Related Blogs

  • author
    Kela Casey

    Tableau vs Power BI vs Qlik Sense | Comparison of Top 3 BI Tools

    Big data is a treasure trove for all types of companies. Every company deserves the best Big Data data analysis and visualization tool. In this post, we will try to provide you with as much detail as possible about the best BI tool for Big Data Visualization. In this segment, we will compare Tableau...

  • author
    Thomas Wilfred

    React Native vs NativeScript: Which To Choose For Cross-Platform App Development

    Cross-platform app development is the process of building mobile apps from a single codebase for Android, Apple OS, and Windows instead of creating separate applications for specific operating systems. While this approach is cost-effective and saves tons of time, developers have had to sacrifice the quality of app performance and user experience previously. Even...

  • author
    Adam Davidson

    Best Online Coding Editors For Beginners

    If you’re a budding web developer or a seasoned coder, you’ll need a code editor that can handle anything you throw at it. In reality, it’s possible that this is the most critical aspect of your toolkit. We wanted to set out a few of the best solutions — both free and paid —...

image

About The Author

Kela has 7+ years of experience in JavaScript, Python, C++, and Java. She’s worked as a software engineer at Google on the Maps JavaScript API, at Biarri automating and optimizing Australia’s fiber network designs.

Try our One-Week Risk Free Trial for Hiring a Coder

Know more Hire a Coder

Hire Top 1% Remote Developers, Free For The First Week

Connect with quality remote developers and code your ideas away.

X