What is the React onClick Event Handler?
In React, the onClick handler enables you to call a function and perform an action when an element is clicked. onClick is the cornerstone of any React app.
Event handlers are made to identify what action is to be taken whenever an event is shot. This could be a mouse click or a change in a text input. In this post, we will look at a few examples of React onClick Event Handler.
In React apps, events are written in the CamelCase format, which means the onclick event will be written as onClick in a React app.
React event handlers are written inside curly braces:
onClick={shoot} instead of onClick="shoot()".
React Example-
To prevent the default link behavior of opening a new page, you can write:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
Click me
);
}
Using the inline function to pass in additional arguments to a function-
import React from 'react';
function App() {
return (
);
}
export default App;
Event handlers recognize what action needs to be taken when an event occurs. The onClick event is used to listen for click events on DOM elements. I have given multiple React onClick Event Handling examples after which things might be a little clearer to you.
Top comments (0)