React Events
React Events are actions that users or the browser perform on a React application, such as clicking, typing, or hovering. These events are built on React’s synthetic event system, providing consistent behavior across browsers.
Handling Events in React
Basic Syntax
In React:
- Event names are written in camelCase (e.g.,
onClick). - Functions are passed as event handlers instead of strings.
Example: Handling a Button Click
import React from "react";
function App() {
const handleClick = () => {
alert("Button clicked!");
};
return (
<button onClick={handleClick}>Click Me</button>
);
}
export default App;Key Differences From DOM Events
- Naming: React uses camelCase (e.g.,
onClickinstead ofonclick). - Function Reference: Pass a function reference, not a string.
- Synthetic Events: Events are wrapped in a cross-browser wrapper.
Common React Events
Mouse Events
- onClick: Triggered when an element is clicked.
- onDoubleClick: Triggered on a double-click.
- onMouseEnter / onMouseLeave: Triggered when the mouse enters or leaves an element.
- onMouseMove: Triggered when the mouse moves over an element.
Example: Mouse Events
function MouseEvents() {
const handleMouseEnter = () => console.log("Mouse entered!");
const handleMouseLeave = () => console.log("Mouse left!");
return (
<div
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
style={{ border: "1px solid black", padding: "20px" }}
>
Hover over this box
</div>
);
}Keyboard Events
- onKeyPress (deprecated): Triggered when a key is pressed.
- onKeyDown: Triggered when a key is pressed down.
- onKeyUp: Triggered when a key is released.
Example: Keyboard Events
function KeyboardEvents() {
const handleKeyDown = (event) => {
console.log(`Key pressed: ${event.key}`);
};
return (
<input type="text" placeholder="Type something..." onKeyDown={handleKeyDown} />
);
}Form Events
- onChange: Triggered when the value of an input changes.
- onSubmit: Triggered when a form is submitted.
- onFocus / onBlur: Triggered when an input gains or loses focus.
Example: Form Events
function FormEvents() {
const handleChange = (event) => console.log(event.target.value);
const handleSubmit = (event) => {
event.preventDefault();
console.log("Form submitted!");
};
return (
<form onSubmit={handleSubmit}>
<input type="text" onChange={handleChange} placeholder="Enter name" />
<button type="submit">Submit</button>
</form>
);
}Passing Arguments to Event Handlers
You can pass additional arguments to event handlers using an inline function.
Example: Passing Arguments
function ArgumentEvents() {
const handleClick = (message) => {
alert(message);
};
return (
<button onClick={() => handleClick("Hello from React!")}>
Click Me
</button>
);
}Get PΛWΛN’s stories in your inbox
Join Medium for free to get updates from this writer.
Event Binding
In React, binding is necessary for class components when referencing this.
Example: Binding in Class Components
import React, { Component } from "react";
class EventBinding extends Component {
constructor() {
super();
this.state = { count: 0 };
this.handleClick = this.handleClick.bind(this); // Binding
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<button onClick={this.handleClick}>
Count: {this.state.count}
</button>
);
}
}
export default EventBinding;Event Propagation
React provides ways to control event propagation:
- Prevent Default: Prevents the browser’s default behavior.
- Stop Propagation: Stops the event from bubbling up the DOM tree.
Example: Prevent Default
function PreventDefault() {
const handleSubmit = (event) => {
event.preventDefault();
alert("Form submission prevented!");
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}Example: Stop Propagation
function StopPropagation() {
const outerDivClick = () => console.log("Outer Div Clicked!");
const innerDivClick = (event) => {
event.stopPropagation();
console.log("Inner Div Clicked!");
};
return (
<div onClick={outerDivClick} style={{ padding: "20px", background: "lightblue" }}>
<div onClick={innerDivClick} style={{ padding: "10px", background: "lightgreen" }}>
Click Me
</div>
</div>
);
}Custom Events
React doesn’t have built-in support for custom events, but you can use state and props to handle them.
Example: Custom Event
function CustomEvent({ onCustomEvent }) {
return (
<button onClick={() => onCustomEvent("Custom event triggered!")}>
Trigger Custom Event
</button>
);
}
function App() {
const handleCustomEvent = (message) => console.log(message);
return <CustomEvent onCustomEvent={handleCustomEvent} />;
}Event Handling in Class vs Function Components
Class Component Example
import React, { Component } from "react";
class ClassEvent extends Component {
handleClick() {
alert("Clicked from Class Component!");
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}
export default ClassEvent;Function Component Example
import React from "react";
function FunctionEvent() {
const handleClick = () => alert("Clicked from Function Component!");
return <button onClick={handleClick}>Click Me</button>;
}
export default FunctionEvent;Event Object
The event object is automatically passed to the event handler.
Example: Using Event Object
function EventObjectExample() {
const handleChange = (event) => {
console.log(event.target.value); // Logs input value
};
return <input type="text" onChange={handleChange} />;
}Conditional Rendering
Conditional rendering means dynamically deciding what to display based on certain conditions, like user actions or state.
Using if-else
function IfElseExample() {
const isLoggedIn = true;
if (isLoggedIn) {
return <h1>Welcome Back!</h1>;
} else {
return <h1>Please Log In</h1>;
}
}Using Ternary Operator
function TernaryExample() {
const isLoggedIn = false;
return (
<div>
{isLoggedIn ? <h1>Welcome Back!</h1> : <h1>Please Log In</h1>}
</div>
);
}Using Logical AND (&&)
Render content only when the condition is true.
Example
function LogicalAndExample() {
const hasMessages = true;
return (
<div>
{hasMessages && <h1>You have new messages!</h1>}
</div>
);
}Combining Events with Conditional Rendering
Example: Toggling UI Components
function ToggleExample() {
const [isVisible, setIsVisible] = React.useState(true);
const toggleVisibility = () => {
setIsVisible((prev) => !prev);
};
return (
<div>
<button onClick={toggleVisibility}>
{isVisible ? "Hide" : "Show"} Text
</button>
{isVisible && <p>This is some text!</p>}
</div>
);
}








