React Events
Just like HTML, React can perform actions based on user events. React has the same events as HTML: click, change, mouseover, etc.
Adding Events
React events are written in camelCase syntax:
onClickinstead ofonclickonChangeinstead ofonchangeonSubmitinstead ofonsubmit
HTML Example:
<button onclick="shoot()">Take the shot!</button>
React Example:
<button onClick={shoot}>Take the shot!</button>
Event Handlers
Here's a simple example of a button click event:
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
onClick={shoot} not onClick={shoot()}
Passing Arguments
To pass an argument to an event handler, use an arrow function:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>
Take the shot!
</button>
);
}
React Event Object
Event handlers have access to the React event that triggered the function:
function Football() {
const shoot = (a, b) => {
alert(b.type);
// 'b' represents the React event
// In this case, the 'click' event
}
return (
<button onClick={(event) => shoot("Goal!", event)}>
Take the shot!
</button>
);
}
Common Event Types
Mouse Events
onClick- Fires when clickedonDoubleClick- Fires when double-clickedonMouseEnter- Fires when mouse entersonMouseLeave- Fires when mouse leavesonMouseMove- Fires when mouse moves
function MouseEvents() {
const handleClick = () => console.log("Clicked!");
const handleHover = () => console.log("Hovering!");
return (
<button
onClick={handleClick}
onMouseEnter={handleHover}
>
Hover or Click Me
</button>
);
}
Keyboard Events
onKeyDown- Fires when a key is pressedonKeyUp- Fires when a key is releasedonKeyPress- Fires when a key is pressed (deprecated)
function KeyboardEvents() {
const handleKeyPress = (event) => {
console.log("Key pressed:", event.key);
};
return (
<input
type="text"
onKeyDown={handleKeyPress}
placeholder="Type something..."
/>
);
}
Form Events
onChange- Fires when value changesonSubmit- Fires when form is submittedonFocus- Fires when element gets focusonBlur- Fires when element loses focus
function FormEvents() {
const handleChange = (event) => {
console.log("Value changed:", event.target.value);
};
const handleFocus = () => {
console.log("Input focused");
};
return (
<input
type="text"
onChange={handleChange}
onFocus={handleFocus}
/>
);
}
Event Handler with State
Combining events with state to create interactive components:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
const handleDecrement = () => {
setCount(count - 1);
};
const handleReset = () => {
setCount(0);
};
return (
<div>
<h1>Count: {count}</h1>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
<button onClick={handleReset}>Reset</button>
</div>
);
}
Preventing Default Behavior
Use event.preventDefault() to prevent default browser behavior:
function MyForm() {
const handleSubmit = (event) => {
event.preventDefault(); // Prevents page refresh
console.log("Form submitted!");
};
return (
<form onSubmit={handleSubmit}>
<input type="text" />
<button type="submit">Submit</button>
</form>
);
}
Event Pooling (Legacy)
In React 16 and earlier, events were pooled for performance. In React 17+, this is no longer the case:
// In React 17+, this works fine:
const handleClick = (event) => {
setTimeout(() => {
console.log(event.type); // Works!
}, 1000);
};
Inline Event Handlers
You can write event handlers inline, but it's not recommended for complex logic:
// Simple inline handler (OK for simple logic)
<button onClick={() => console.log("Clicked")}>
Click Me
</button>
// Better: Define handler separately
const handleClick = () => {
console.log("Clicked");
};
<button onClick={handleClick}>Click Me</button>
Multiple Events on One Element
You can attach multiple event handlers to a single element:
function MultipleEvents() {
const handleClick = () => console.log("Clicked!");
const handleMouseEnter = () => console.log("Mouse entered!");
const handleMouseLeave = () => console.log("Mouse left!");
return (
<button
onClick={handleClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
Hover and Click Me
</button>
);
}
Real-World Example: Toggle Button
import { useState } from "react";
function ToggleButton() {
const [isOn, setIsOn] = useState(false);
const handleToggle = () => {
setIsOn(!isOn);
};
return (
<div>
<button
onClick={handleToggle}
style={{
backgroundColor: isOn ? "green" : "gray",
color: "white",
padding: "10px 20px"
}}
>
{isOn ? "ON" : "OFF"}
</button>
</div>
);
}
Real-World Example: Input with Live Feedback
import { useState } from "react";
function LiveInput() {
const [text, setText] = useState("");
const handleChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input
type="text"
value={text}
onChange={handleChange}
placeholder="Type something..."
/>
<p>You typed: {text}</p>
<p>Character count: {text.length}</p>
</div>
);
}
Event Handler Best Practices
- Use camelCase for event names (onClick, onChange)
- Pass functions, not function calls (onClick={handler}, not onClick={handler()})
- Use arrow functions when you need to pass arguments
- Prevent default when needed (e.g., form submissions)
- Keep handlers simple - extract complex logic to separate functions
- Name handlers clearly - use handle prefix (handleClick, handleSubmit)
What's Next?
Now that you understand events, you're ready to learn about Forms - how to handle user input in React applications!