REACT
React events manage user interactions like clicks, form submissions, and key presses. They use synthetic events, which wrap native browser events for cross-browser compatibility.
How to Use React Events
React event handlers use camelCase, such as onClick
and onChange
. Unlike HTML, where event attributes take strings, React assigns functions.
Basic Event Handling
function ClickHandler() {
const handleClick = () => {
console.log("Button clicked!");
};
return <button onClick={handleClick}>Click Me</button>;
}
React automatically passes the event object when the button is clicked.
Accessing the Event Object
React provides a Synthetic Event that normalizes event properties across browsers. You can access details like event.target.value
or event.key
.
function InputHandler() {
const handleInput = (event) => {
console.log("Input value:", event.target.value);
};
return <input type="text" onChange={handleInput} />;
}
Passing Arguments to Event Handlers
To pass custom arguments while keeping access to the event, use an arrow function inside the handler.
function CustomClick() {
const handleClick = (message, event) => {
console.log(message, event.type);
};
return <button onClick={(e) => handleClick("Button clicked!", e)}>Click</button>;
}
When to Use React Events
React events make user interaction handling more efficient and prevent unnecessary re-renders.
Handling Form Submissions
Forms need event handling to manage user input and prevent default behavior.
function FormSubmit() {
const handleSubmit = (event) => {
event.preventDefault();
console.log("Form submitted!");
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Detecting Key Presses
Keyboard events allow you to trigger actions when users press specific keys.
function KeyPressHandler() {
const handleKeyPress = (event) => {
if (event.key === "Enter") {
console.log("Enter key pressed!");
}
};
return <input type="text" onKeyDown={handleKeyPress} />;
}
Handling Mouse Events
Mouse events detect clicks, double clicks, and hover interactions.
function HoverBox() {
const handleHover = () => {
console.log("Mouse hovered over the box!");
};
return <div onMouseOver={handleHover} style={{ width: 100, height: 100, background: "lightblue" }} />;
}
Examples of React Events
Logging an Event Object
Printing an event object in React shows a Synthetic Event.
function LogEvent() {
const handleClick = (event) => {
console.log(event);
};
return <button onClick={handleClick}>Log Event</button>;
}
If the event disappears in an asynchronous function, use event.persist()
.
function AsyncEvent() {
const handleClick = (event) => {
event.persist();
setTimeout(() => {
console.log(event.type);
}, 1000);
};
return <button onClick={handleClick}>Delayed Event Log</button>;
}
Synthetic Events vs. Native Events
React wraps browser events in synthetic events to standardize them. You can still access the native event using event.nativeEvent
.
function NativeEvent() {
const handleClick = (event) => {
console.log("React Event:", event);
console.log("Native Event:", event.nativeEvent);
};
return <button onClick={handleClick}>Check Events</button>;
}
Event Listeners in React
React attaches events to the Virtual DOM, not the actual DOM. If you need to listen for global events (like resize
or scroll
), use useEffect()
.
import { useEffect } from "react";
function WindowResize() {
useEffect(() => {
const handleResize = () => {
console.log("Window resized");
};
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return <p>Resize the window and check the console.</p>;
}
Learn More About React Events
Is Date an Event in React?
Date
is not an event in React. If you see a date while logging an event, it's likely from another function or API response.
How to Print an Event in React?
Log the event inside a handler:
const handleEvent = (event) => console.log(event);
If the event disappears, use event.persist()
.
React Event for Component Loaded as a Prop
Use useEffect()
to trigger an event when a component receives a new prop.
import { useEffect } from "react";
function ComponentWithProp({ propValue }) {
useEffect(() => {
console.log("Prop changed:", propValue);
}, [propValue]);
return <p>{propValue}</p>;
}
React Synthetic Events
Synthetic events provide a consistent way to handle interactions across browsers. If needed, access the native event with event.nativeEvent
.
function SyntheticExample() {
const handleClick = (event) => {
console.log("Synthetic Event:", event);
console.log("Native Event:", event.nativeEvent);
};
return <button onClick={handleClick}>Synthetic vs Native</button>;
}
Handling Global Events in React
React does not automatically handle global events like scroll
or resize
. Use useEffect()
with native event listeners.
import { useEffect } from "react";
function ScrollLogger() {
useEffect(() => {
const handleScroll = () => console.log("User scrolled");
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <p>Scroll to see logs in the console.</p>;
}
React Event Handling vs. Traditional DOM Events
- React event names use camelCase (
onClick
), while native events use lowercase (onclick
). - React events attach to the Virtual DOM, while native events attach to the actual DOM.
- Synthetic events wrap native events, ensuring consistency across browsers.
- Native event handling requires manual cross-browser support.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.