~/
hackweb.dev
Event Handling
Quiz
⌘K
...
~/
/tutorials
/react/react-events/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/react/6react-events
Write
Preview
Diff
# Event Handling React uses synthetic events that wrap the browser's native events, providing consistent cross-browser behavior. ## onClick ```jsx function Button() { function handleClick() { alert("Clicked!"); } return <button onClick={handleClick}>Click me</button>; } ``` Pass a function reference, don't call it: `onClick={handleClick}`, not `onClick={handleClick()}`. ## onChange ```jsx function Input() { const [value, setValue] = useState(""); return ( <input value={value} onChange={(e) => setValue(e.target.value)} /> ); } ``` The event object `e` gives you access to the input's current value. ## The Event Object React events are **synthetic events** — thin wrappers around native events: ```jsx function Form() { function handleSubmit(e) { e.preventDefault(); console.log(e.target.value); } return <form onSubmit={handleSubmit}>...</form>; } ``` They have the same interface as native events but work identically across browsers. ## Preventing Default Use `e.preventDefault()` to stop default browser behavior: ```jsx function Link({ href, children }) { function handleClick(e) { e.preventDefault(); console.log("Navigation blocked"); } return <a href={href} onClick={handleClick}>{children}</a>; } ``` Without it, clicking a link navigates away from the page. ## Passing Arguments Use an arrow function to pass custom arguments: ```jsx function TodoList({ items }) { function handleDelete(id) { console.log("Delete", id); } return items.map(item => ( <li key={item.id} onClick={() => handleDelete(item.id)}> {item.text} </li> )); } ``` Without the arrow function, `handleDelete(item.id)` runs on render, not on click. ## Common Event Handlers | Event | Handler | |-------|---------| | Click | `onClick` | | Input change | `onChange` | | Form submit | `onSubmit` | | Key press | `onKeyDown`, `onKeyUp` | | Mouse enter | `onMouseEnter` | | Focus | `onFocus`, `onBlur` | ## Best Practices 1. **Use descriptive names** — `handleClick`, `handleSubmit`, not `onClick` 2. **Define handlers inside or outside component** — Both work 3. **Use arrow functions for arguments** — `() => handleDelete(id)` 4. **Prevent default early** — First line in form handlers ## Common Mistakes 1. **Calling the function in JSX** — `onClick={handleClick()}` runs immediately 2. **Forgetting preventDefault** — Forms submit and reload the page 3. **Using `this` in function components** — There is no `this` context 4. **Not destructuring the event** — `e.target.value` requires the event param
No changes yet
Reset to original
Submit suggestion
cancel