State and events · Lesson 6 of 21
Handling events
onClick and onChange, passing a function rather than calling it, and the event object.
7 minutes2 games
To respond to the user, pass a function to an element through a prop like onClick, onChange or onSubmit. React calls it when the event happens and hands it an event object with the details.
React
function App() {
function handleClick() {
alert("Saved!")
}
return (
<div>
<button onClick={handleClick}>Save</button>
<button onClick={() => console.log("clicked at", new Date().toLocaleTimeString())}>Log time</button>
<input placeholder="Type here" onChange={(e) => console.log(e.target.value)} />
</div>
)
}React
function Toolbar({ onAction }) {
return (
<div style={{ display: "flex", gap: 8 }}>
{["Copy", "Run", "Share"].map((label) => (
<button key={label} onClick={() => onAction(label)}>{label}</button>
))}
</div>
)
}
function App() {
return <Toolbar onAction={(name) => console.log("You pressed " + name)} />
}The parent passes onAction as a prop
A button in the child is clicked
The child calls onAction("Run")
The parent's code runs
This lets a child "report" to its parent without knowing what it will do.
Spot the bug
The alert appears as soon as the page loads, not on click. Which line?
Quick question
Which is right for deleting the item with id on click?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.