Loading...

React lets us add event handlers in our JSX. Event handlers are functions that run in response to user interactions such as clicking, hovering, and focusing. Let's understand this step by step.
To add an event handler, we define a function and then pass it to an event like onClick in JSX.
export default function Button() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}It is a common convention to name event handler functions starting with handle, such as handleClick, handleMouseEnter, etc.
We can also define event handlers inline for short functions:
<button onClick={function handleClick() {
alert('You clicked me!');
}}>
Click Me
</button>You must pass the function reference, not call it.
// Correct
<button onClick={handleClick}>
// Incorrect
<button onClick={handleClick()}>In the correct example, we pass the function so React can call it later when the user clicks. In the incorrect example, adding () calls the function immediately during render.
In the browser, when you click a child element, the event bubbles up to its parent and then up the tree. This is called event propagation, and React follows the same behavior.
We can stop a bubbling event using e.stopPropagation().
function handleClick(e) {
e.stopPropagation();
alert('Clicked only this!');
}This is useful when both parent and child have event handlers but we want to run only the child's handler.
Sometimes we want to stop the browser's default actions — like form submission causing a page refresh. We use e.preventDefault() to stop this.
function handleSubmit(e) {
e.preventDefault();
alert('Form submitted!');
}
return (
<form onSubmit={handleSubmit}>
<button type='submit'>Submit</button>
</form>
);Lastly, remember React's naming convention: event handlers usually start with handle, such as handleClick.