π±οΈ Handling Events in React
React uses a slightly different approach to handling browser events. You can pass event handlers as props directly into elements using camelCase syntax.
π Basic Event Example
function ClickButton() {
function handleClick() {
alert("Button was clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}
β‘ Inline Event Handler
You can define the function directly inside the JSX:
<button onClick={() => alert("Clicked!")}>Click</button>
π¨ Accessing Event Object
React automatically passes the event object to your handler:
function handleClick(event) {
console.log(event.target);
}
π« Preventing Default Behavior
function MyForm() {
function handleSubmit(e) {
e.preventDefault();
alert("Form submitted!");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
π§ No Need for Binding
In modern React (with function components), you donβt need to bind this
like in class components. Arrow functions preserve scope naturally.
β Best Practices
- Use named functions for better readability and debugging.
- Avoid inline functions if performance is a concern (e.g. large lists).
- Use
preventDefault()
for forms or anchor tags when needed.
π Summary
- Use
onClick
,onChange
,onSubmit
, etc. with camelCase syntax. - Arrow functions keep
this
binding clean. - React normalizes events across browsers.