React JS App: events
ReactJS events
1 Overview
📘 events React lets you add event handlers to your JSX.
Event handlers are your own functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
2 Adding event handlers
You can make it show a message when a user clicks by following these three steps:
- Declare a function called
handleClick
inside yourButton
component. - Implement the logic inside that function (use
alert
to show the message). - Add
onClick={handleClick}
to the<button> JSX
.
Event handler functions are usually defined inside your components
app.jsx
You defined the handleClick
function and then passed it as a prop
to <button>
. handleClick
is an event handler
Functions passed to event handlers must be passed, not called. For example:
- passing a function (correct):
<button onClick={handleClick}>
- calling a function (incorrect):
<button onClick={handleClick()}>
The difference is subtle. In the first example, the handleClick
function is passed as an onClick
event handler. This tells React to remember it and only call your function when the user clicks the button.
In the second example, the ()
at the end of handleClick()
fires the function immediately during rendering, without any clicks. This is because JavaScript
inside the JSX { and }
executes right away.
3 Passing event handlers as props
Often you’ll want the parent component to specify a child’s event handler. Consider buttons: depending on where you’re using a Button
component, you might want to execute a different function—perhaps one plays a movie and another uploads an image.
To do this, pass a prop the component receives from its parent as the event handler
like so:
index.js
function Button({ onClick, children }) {
return (
<button onClick={onClick}>
{children}
</button>
);
}
function PlayButton({ movieName }) {
function handlePlayClick() {
alert(`Playing ${movieName}!`);
}
return (
<Button onClick={handlePlayClick}>
Play "{movieName}"
</Button>
);
}
function UploadButton() {
return (
<Button onClick={() => alert('Uploading!')}>
Upload Image
</Button>
);
}
export default function Toolbar() {
return (
<div>
<PlayButton movieName="Kiki's Delivery Service" />
<UploadButton />
</div>
);
}
Here, the Toolbar
component renders a PlayButton
and an UploadButton
:
PlayButton
passeshandlePlayClick
as theonClick
prop to theButton
inside.UploadButton
passes() => alert('Uploading!')
as theonClick
prop to theButton
inside.
Finally, your Button
component accepts a prop called onClick
. It passes that prop directly to the built-in browser <button>
with onClick={onClick}
. This tells React to call the passed function on click.