One of the essential aspects of any web application is how users interact with it. Most interactions happen through events, such as clicks, key presses, or form submissions. React provides a clean way to handle these events using event handlers. In this blog, we’ll explore how React manages events and forms in a way that makes your web apps dynamic, responsive, and user-friendly.
By the end of this blog, you’ll know how to:
Handle basic events like clicks and form submissions in React.
Create controlled components to manage form data efficiently.
Manage validation and custom form logic.
Apply event handling patterns to more advanced use cases.
Let’s dive in!
What Are Events in React?
Events are actions taken by users or triggered programmatically. In React, events are handled similarly to how we manage them in plain JavaScript but with a few differences:
Events are camelCased in React (
onClick
,onSubmit
, etc.) instead of being lowercase.You pass a function (event handler) to the event, not a string.
Basic Event Handling
Let’s begin with a simple example of handling a click event in React.
jsxCopy codeimport React from 'react';
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<div>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
export default App;
Here, we attach the handleClick
function to the onClick
event of the button. When the button is clicked, the function executes, triggering the alert box.
Passing Arguments to Event Handlers
Sometimes, you might want to pass arguments to your event handlers. You can achieve this by wrapping the event handler in an anonymous function.
jsxCopy codeimport React from 'react';
function App() {
function handleClick(name) {
alert(`Hello, ${name}!`);
}
return (
<div>
<button onClick={() => handleClick('John')}>Click Me</button>
</div>
);
}
export default App;
In this example, the handleClick
function accepts a name
parameter, and when the button is clicked, it will show "Hello, John!" in the alert.
Handling Forms in React
Forms are critical in web applications as they are the primary way users input and submit data. In React, handling forms is different from traditional HTML because React uses something called controlled components.
Controlled Components
A controlled component is a form element that is controlled by React. The state of the component is kept in sync with the React component's state, making the form element’s value a controlled source of truth.
Let’s look at an example of how to handle a form input.
jsxCopy codeimport React, { useState } from 'react';
function App() {
const [name, setName] = useState('');
function handleChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
alert(`Form submitted with name: ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default App;
Here’s what’s happening:
State Management: We use
useState
to manage thename
state.Handling Input Changes: The
handleChange
function updates the state whenever the user types in the input field.Form Submission: The
handleSubmit
function is attached to theonSubmit
event of the form. It prevents the default form behavior usingevent.preventDefault()
and displays the submitted name using an alert.
Multiple Input Fields
In real-world applications, forms often have multiple input fields. Handling them individually can get tedious. Let’s look at how to manage multiple fields efficiently.
jsxCopy codeimport React, { useState } from 'react';
function App() {
const [formData, setFormData] = useState({
name: '',
email: '',
});
function handleChange(event) {
const { name, value } = event.target;
setFormData(prevFormData => ({
...prevFormData,
[name]: value,
}));
}
function handleSubmit(event) {
event.preventDefault();
alert(`Form submitted: ${formData.name}, ${formData.email}`);
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default App;
Here’s how this works:
We store all form data in one state object (
formData
).The
handleChange
function updates the specific field in the state using thename
attribute from the input element.This way, we manage the entire form’s state in a single state object, simplifying the code.
Textarea and Select Elements
Handling <textarea>
and <select>
elements in React is similar to handling input fields. You still need to control the component’s value using state.
Example: Handling a textarea
jsxCopy codeimport React, { useState } from 'react';
function App() {
const [message, setMessage] = useState('');
function handleChange(event) {
setMessage(event.target.value);
}
return (
<div>
<textarea value={message} onChange={handleChange} />
</div>
);
}
export default App;
Example: Handling a select
jsxCopy codeimport React, { useState } from 'react';
function App() {
const [selectedOption, setSelectedOption] = useState('option1');
function handleChange(event) {
setSelectedOption(event.target.value);
}
return (
<div>
<select value={selectedOption} onChange={handleChange}>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</div>
);
}
export default App;
Both the <textarea>
and <select>
elements use the same logic as input fields, controlled by React state and updated through the onChange
event.
Form Validation
Now that we know how to handle form elements, let's introduce some validation. This is crucial in ensuring the user submits valid data. Validation can be done either inline (on the client side) or server-side, but for this example, we’ll focus on simple client-side validation.
Example: Basic Form Validation
jsxCopy codeimport React, { useState } from 'react';
function App() {
const [formData, setFormData] = useState({
name: '',
email: '',
});
const [errors, setErrors] = useState({});
function handleChange(event) {
const { name, value } = event.target;
setFormData(prevFormData => ({
...prevFormData,
[name]: value,
}));
}
function validate() {
const newErrors = {};
if (!formData.name) newErrors.name = "Name is required";
if (!formData.email) newErrors.email = "Email is required";
return newErrors;
}
function handleSubmit(event) {
event.preventDefault();
const validationErrors = validate();
if (Object.keys(validationErrors).length === 0) {
alert(`Form submitted: ${formData.name}, ${formData.email}`);
} else {
setErrors(validationErrors);
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
{errors.name && <span>{errors.name}</span>}
</label>
<br />
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
{errors.email && <span>{errors.email}</span>}
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default App;
In this example:
Validation Logic: We check if both the name and email fields are filled out before allowing the form submission.
Error Handling: We store validation errors in the
errors
state object and display them next to the respective fields if they are not valid.
Conclusion
Handling events and forms in React involves understanding how to work with controlled components and event handlers.
Thank you for reading till here. If you want learn more then ping me personally and make sure you are following me everywhere for the latest updates.
Yours Sincerely,
Sai Aneesh