React provides a seamless way to handle user interactions through events. Similar to HTML DOM events, React supports events like click
, change
, mouseover
, and many more.
React events differ slightly in syntax but are easy to work with once understood.
Adding Events
In React, events are:
- CamelCase: Use
onClick
instead ofonclick
. - Wrapped in Curly Braces: Event handlers are passed inside curly braces, e.g.,
onClick={handleClick}
instead ofonclick="handleClick()"
.
Example:
Here’s how you can handle a click
event in React:
function ActionButton() {
const handleClick = () => {
alert("Button Clicked!");
};
return <button onClick={handleClick}>Click Me!</button>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ActionButton />);
In this example, clicking the button triggers the handleClick
function, showing an alert box.
Passing Arguments to Event Handlers
You can pass arguments to an event handler using arrow functions.
Example:
function GoalButton() {
const showMessage = (message) => {
alert(message);
};
return <button onClick={() => showMessage("Goal!")}>Shoot the Goal!</button>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<GoalButton />);
Here, the "Goal!"
message is passed to the showMessage
function when the button is clicked.
React Event Object
React event handlers have access to the event object, which contains information about the event that was triggered.
Example:
function InfoButton() {
const handleEvent = (message, event) => {
alert(`Message: ${message}, Event Type: ${event.type}`);
};
return (
<button onClick={(event) => handleEvent("Event Captured", event)}>
Click for Info
</button>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<InfoButton />);
In this example, the event
object is captured and its type
is displayed alongside a custom message.
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment