"In the real world, you wave and someone smiles. In React, you click and a function runs."
In this guide, we dive deep into event handling in React — the essential skill that turns your UI from static to dynamic and interactive.
What is an Event?
Events are any interactions users have with the app: clicks, typing, scrolling, submitting, hovering, etc. Handling these events is what lets your app react to the user.
React vs HTML Event Syntax
HTML | React |
---|---|
<button onclick="doSomething()"> | <button onClick={doSomething}> |
lowercase | camelCase |
string handler | function reference |
Basic onClick Example
function App() {
function handleClick() {
alert("Button was clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}
Common React Events
onClick
– clicking a buttononChange
– input field changeonSubmit
– form submissiononMouseEnter
,onMouseLeave
– hover eventsonKeyDown
,onKeyUp
– keyboard eventsonFocus
,onBlur
– input focus and blur
Passing Arguments
function greet(name) {
alert(`Hello, ${name}`);
}
<button onClick={() => greet("Alice")}>Greet Alice</button>
Accessing the Event Object
function handleClick(event) {
console.log(event.target);
}
Controlled Input Example
function TextBox() {
const [text, setText] = useState("");
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<p>Typed: {text}</p>
</>
);
}
Form Handling
function Login() {
const [email, setEmail] = useState("");
function handleSubmit(e) {
e.preventDefault();
alert(`Logging in with ${email}`);
}
return (
<form onSubmit={handleSubmit}>
<input type="email" onChange={e => setEmail(e.target.value)} />
<button>Login</button>
</form>
);
}
Hover Effects
function HoverCard() {
return (
<div
onMouseEnter={() => console.log("Mouse over")}
onMouseLeave={() => console.log("Mouse left")}
>
Hover over me!
</div>
);
}
Parent to Child Events
function Child({ onCustomClick }) {
return <button onClick={onCustomClick}>Call Parent</button>;
}
function Parent() {
return <Child onCustomClick={() => alert("Child clicked!")} />;
}
Common Mistakes
- Calling function directly:
onClick={handleClick()}
(WRONG) - Forgetting
e.preventDefault()
in form handling - Trying to use
this
in functional components
Best Practices
- Use arrow functions to pass parameters
- Define event handlers outside JSX for clarity
- Use descriptive function names like
handleLogin
Example: Like Button
function LikeButton() {
const [liked, setLiked] = useState(false);
return (
<button onClick={() => setLiked(prev => !prev)}>
{liked ? " Liked" : "🤍 Like"}
</button>
);
}
Keyboard Events
function KeyLogger() {
return <input onKeyDown={e => console.log(e.key)} />;
}
Combining with useEffect
useEffect(() => {
const handleEsc = e => {
if (e.key === "Escape") {
console.log("Escape pressed");
}
};
window.addEventListener("keydown", handleEsc);
return () => window.removeEventListener("keydown", handleEsc);
}, []);
Mastering event handling in React unlocks the power of user interactivity. From clicks to key presses, each interaction brings your app to life.
"React without event handling is like a guitar without strings – you can hold it, but you can't make music."
0 Comments:
Post a Comment