react · source-driven
Responding to events
Declare event handler functions inside your component and pass them to props like onClick — do not call them while rendering.
Official docs: react.dev/learn — Responding to events
You will learn
- How to declare an event handler inside a component
- How to pass a function to onClick (without calling it)
- That naming is often handleClick / onClick by convention
Pass the function, don’t call it
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}Try it
Recap
- Event handlers are functions defined in your component
- Pass the function reference to onClick / onChange / onSubmit
- React calls it when the browser event happens
Challenge
Try this
Add an onChange handler on an input that console.logs the value. Remember: e.target.value.