In this tutorial, we are going to learn, how to do the click event using React. Previously I had written an article about “How to Create Your First React Project”. We can do the click event using the onClick property of JSX.
Simple Button Click:
First, create a simple function in the App.js like below.
- The simpleClick() is the function and it is an arrow function.
- We can use let, var, const in the arrow function prefix. The const is preferred by many developers.
Now bind the function to a button using the onClick property.
- Use a single curly brace to bind the function with the onClick property.
- No need to use the parenthesis for the function in the onClick property. Parenthesis are needed only if we had parameter for a function.
Save the above code and click the button. It will print the
“simple click event”
as output in the console of your browser.
Pass Parameter to Function While Clicking:
Calling a function with parameters is not a simple and straightforward task in React. That’s why I created this section. To pass a parameter to a function in the click event, we have to use the anonymous function.
Create a function with a parameter in the App.js file like below.
Now bind the created function with a button click event using the anonymous function like below.
Call the anotherClick() function inside the anonymous function.
React is a little bit different in this click event when compared to Angular and Vue. In Angular and Vue, there is no need for an anonymous function to call a function with a parameter.
Pass Event Object to Function While Clicking:
In React we simply use the keyword “e” to use the event object. Create a function with an event object like below.
Binding the function with click events is very easy. Why because the event object “e” is not considered as a parameter. So we can call it simply with onClick property like below.
Pass Event Object to Function With Parameter While Clicking:
In function, with parameter, pass the event object after the parameter like below.
To bind this parameterized function with the click event, use the event object “e” in the anonymous function like below.
In this tutorial, you learned how to bind the click event with functions using different types. It is a second tutorial in the React tutorial series. Stay tuned for more articles.
Thank you for reading.