Event Handling
Handling events with React elements is very similar to handling events on DOM elements. However, there are some syntax differences you should be aware of.
Syntactic Differences
- React events are named using camelCase (e.g., onClick instead of onclick).
- With JSX you pass a function as the event handler, rather than a string.
Basic Click Event
In React, you don't call the function in the attribute; you provide a reference to it.
JavaScript
function ActionButton() {
function handleClick() {
alert('Button clicked!');
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
} Preventing Default Behavior
In React, you cannot return false to prevent default behavior. You must call preventDefault explicitly on the event object.
JavaScript
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('Form submitted.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
} Note: React's event object is a SyntheticEvent, which is a cross-browser wrapper around the browser’s native event. It has the same interface as the native event.