To handle React events like button clicks, you use event handlers in JSX, similar to how you'd handle events in plain HTML, but with some key React-specific tweaks.
Here’s how you do it:
1. Define an Event Handler Function
You create a function that does something when the button is clicked.
function handleClick() {
alert('Button was clicked!');
}
2. Attach the Event Handler to the Button Using onClick (camelCase)
In React, event names use camelCase (e.g., onClick instead of onclick), and you pass the function without calling it (i.e., no parentheses).
function MyButton() {
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
3. Passing Arguments (Optional)
If you want to pass arguments to your handler, use an arrow function inside onClick:
function handleClick(message) {
alert(message);
}
function MyButton() {
return (
<button onClick={() => handleClick('Hello from the button!')}>
Click Me
</button>
);
}
4. Prevent Default Behavior (e.g., Form Submit)
Use event.preventDefault() inside the handler to stop default actions:
function handleSubmit(e) {
e.preventDefault();
console.log('Form submitted!');
}
function MyForm() {
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}