- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React Events
- React events are the backbone of interactivity. They represent interactions—like clicks, mouse movements, or keystrokes—that trigger specific logic in your application.
- When a user interacts with an element, React catches that interaction using a system called SyntheticEvents, which ensures your code works consistently across all browsers (Chrome, Safari, Firefox, etc.).
Handling Events in React
- React events are named using camelCase rather than lowercase. For example, you use
onClickinstead of the standard HTMLonclick. - With JSX, you pass a function as the event handler rather than a string. Instead of
onclick="handleClick()", you writeonClick={handleClick}.
onClick={handleClick()}. This executes the function immediately when the component renders, rather than waiting for a click. Always pass the function reference: onClick={handleClick}.
Example: Handling Click Events
In modern React, we primarily use functional components. Here is how you define a simple click handler:
import React from 'react';
const ButtonClick = () => {
// Logic lives inside this helper function
const handleClick = () => {
alert('The button was clicked!');
};
return (
<button onClick={handleClick}>Click Me</button>
);
};
While less common in new projects, you may still encounter class components in legacy codebases. Note how this must be handled carefully:
import React, { Component } from 'react';
class ButtonClickClass extends Component {
// Use an arrow function for the method to auto-bind 'this'
handleClick = () => {
alert('Button Clicked from a Class!');
}
render() {
return (
<button onClick={this.handleClick}>Click Me</button>
);
}
}
this will be undefined when the function is called. You would need to manually bind it in the constructor.
Passing Parameters to Event Handlers
Sometimes you need to pass extra data to your handler, such as an ID from a list. To do this, wrap the handler in an anonymous arrow function.
import React from 'react';
const ParameterizedClick = () => {
const deleteUser = (id) => {
console.log(`Deleting user with ID: ${id}`);
};
return (
// We wrap the call in an arrow function to delay execution
<button onClick={() => deleteUser(123)}>Delete User 123</button>
);
};
onClick for every item can slightly impact performance. For most apps, this isn't an issue, but for high-performance needs, consider optimizing with useCallback.
Form Handling
In React, we typically use "Controlled Components." This means the React state is the "single source of truth" for the input's value. When the user types, an event updates the state, and the state updates the input value.
import React, { useState } from 'react';
const FormExample = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
// e.target.value contains the current text in the input
setInputValue(e.target.value);
};
return (
<div>
<p>Current text: {inputValue}</p>
<form>
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type something..."
/>
</form>
</div>
);
};
e) in any handler. It contains useful information like e.target.name, which allows you to use a single handler function for multiple input fields.
Preventing Default Behavior
Standard HTML forms refresh the page when a submit button is clicked. In a Single Page Application (SPA) like React, we usually want to handle the data ourselves without a page reload. We use e.preventDefault() to stop this default browser behavior.
import React from 'react';
const FormPreventDefault = () => {
const handleSubmit = (e) => {
e.preventDefault(); // This stops the page from refreshing!
console.log('Processing form data via API...');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Your Name" />
<button type="submit">Submit</button>
</form>
);
};
Summary
Mastering React events is essential for building real-world applications. By understanding how to hook into user actions, manage state through forms, and control browser behavior with preventDefault, you gain the ability to create highly responsive and fluid user experiences. Remember to stick to camelCase naming and always keep an eye on how you pass function references to maintain clean, bug-free code.