Similar to HTML DOM events, React can handle actions triggered by user events. React supports the same events as HTML, such as click, change, and mouseover.
Adding Events
React events use camelCase syntax, such as onClick instead of onclick. Event handlers in React are written inside curly braces, like onClick={shoot}, rather than onclick=”shoot()”.
React:
<button onClick={shoot}>Take the Shot!</button>
|
HTML:
<button onclick="shoot()">Take the Shot! </button>
|
Example:
Define the shoot function within the Football component.
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Football />);
|
Passing Arguments
To pass an argument to an event handler, utilize an arrow function.
Example:
Pass “Goal!” as an argument to the shoot function by using an arrow function.
function Football() {
const shoot = (a) => {
alert(a );
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Football />);
|
React Event Object
Event handlers have access to the React event that triggered the function, such as the “click” event in our example.
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>
);
}
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Football />);
|