Clean β’ Professional
In React, events make your web app interactive β they let users click buttons, type text, submit forms, and trigger actions. Event handling in React is simple, powerful, and similar to how you handle events in plain JavaScript, but with a few key differences.
Letβs explore how React handles click events, input events, and custom events with clear examples.
In React, events are written in camelCase (e.g., onClick, onChange, onSubmit) instead of lowercase like in HTML.
| HTML | React |
|---|---|
<button onclick="handleClick()"> | <button onClick={handleClick}> |
Also, instead of strings, you pass functions as event handlers.
Example:
<button onClick={handleClick}>Click Me</button>
React uses a concept called Synthetic Events β a wrapper around browser events that ensures consistent behavior across different browsers.
Click events are the most common way to trigger actions in React apps β for example, updating a counter or toggling visibility.
Example β Handling a Click
import React from "react";
function ClickExample() {
function handleClick() {
alert("Button Clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}
export default ClickExample;
onClick (camelCase).handleClick runs only when the button is clicked.Example β Passing Parameters to Event Handlers
function Greeting({ name }) {
const sayHello = (user) => {
alert(`Hello, ${user}!`);
};
return <button onClick={() => sayHello(name)}>Greet {name}</button>;
}
Example β Using Events with State
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h3>Count: {count}</h3>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
Input events allow you to track what users type in text boxes or select from dropdowns. React uses the onChange event to handle user input.
Example β Input Change Event
import React, { useState } from "react";
function InputExample() {
const [text, setText] = useState("");
return (
<div>
<inputtype="text"
placeholder="Type something..."
onChange={(e) => setText(e.target.value)}
/>
<p>You typed: {text}</p>
</div>
);
}
export default InputExample;
onChange event triggers whenever the input value changes.e.target.value gives the current value of the input.text) updates instantly, showing real-time feedback.Example β Handling Form Submission
Reactβs onSubmit works just like in HTML forms, but you often use e.preventDefault() to stop the browserβs default reload behavior.
import React, { useState } from "react";
function FormExample() {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault(); // Prevent page reload
alert(`Form submitted by ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<inputtype="text"
placeholder="Enter your name"
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
}
export default FormExample;
Sometimes, you need custom events to communicate between components β for example, when a child component triggers an action in its parent. React doesnβt use a built-in CustomEvent API like the browser does β instead, you pass functions as props to simulate custom event behavior.
Example β Custom Event Between Components
function Child({ onMessage }) {
return (
<button onClick={() => onMessage("Hello from Child!")}>
Send Message to Parent
</button>
);
}
function Parent() {
const handleMessage = (msg) => {
alert(msg);
};
return (
<div>
<h2>Parent Component</h2>
<Child onMessage={handleMessage} />
</div>
);
}
export default Parent;
handleMessage to the child.onMessage() when clicked β this acts like a custom event.| Event | Description |
|---|---|
onClick | Fires when an element is clicked |
onChange | Triggered when input value changes |
onSubmit | Fired when a form is submitted |
onKeyDown | When a key is pressed |
onMouseOver | When the mouse hovers over an element |
onFocus / onBlur | When an input gains or loses focus |
Example β Combining Multiple Events
import React, { useState } from "react";
function InteractiveExample() {
const [text, setText] = useState("");
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
setSubmitted(true);
};
return (
<div>
<h2>React Event Handling Example</h2>
<form onSubmit={handleSubmit}>
<inputtype="text"
value={text}
placeholder="Type your name"
onChange={(e) => setText(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
{submitted && <p>Welcome, {text || "Guest"}!</p>}
</div>
);
}
export default InteractiveExample;Β