react event
react event
React has the same events as HTML: click, change, mouseover etc.
Adding Events
React events are written in camelCase syntax:
import React from 'react';
import ReactDOM from 'react-dom/client';
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
Passing Arguments
To pass an argument to an event handler, use an arrow function.
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function.
In this case, the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to preve
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}