React Tutorials
React ES6
React Hooks
Like HTML DOM events, React can perform actions based on user events.
React has the same HTML events: click, change, mouseover etc.
React events are recorded with camelCase syntax:
onClick
instead of onclick
.
React event handles are enclosed within the folded parentheses:
onClick={shoot}
instead of onClick="shoot()"
<button onClick={shoot}>Take the Shot!</button>
<button onclick="shoot()">Take the Shot!</button>
Put the shoot
function inside the Football
component:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
To pass an argument to the event handler, use the arrow function.
Send "Goal!" as a parameter to the shoot
function, using arrow function:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
Event hosts have access to the React event that started the task.
In our example event "click" event.
Arrow Function: Sending the event object manually:
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>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
This will be helpful if we look at the Form in the next chapter.