React Forms are an essential part of any interactive web application. They provide a way to collect input from the user and handle user submissions. Here’s a comprehensive guide on how to handle forms in React, covering controlled components, uncontrolled components, form validation, and more.
Controlled components in React are form elements like input, textarea, and select whose value is controlled by React state. Whenever the user interacts with a controlled component, the value is updated via a handler function.
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
alert('Name submitted: ' + name);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
In uncontrolled components, the form data is handled by the DOM itself instead of the React component. React refs are used to access the values directly from the DOM.
import React from 'react';
class UncontrolledForm extends React.Component {
constructor(props) {
super(props);
this.nameInput = React.createRef();
}
handleSubmit = (event) => {
event.preventDefault();
alert('Name submitted: ' + this.nameInput.current.value);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.nameInput} />
</label>
<button type="submit">Submit</button>
</form>
);
}
}
export default UncontrolledForm;
Validation is essential to ensure that users are submitting the correct type of data. The validation process can involve checking for required fields, verifying the format of the data, etc.
import React, { useState } from 'react';
function ValidationForm() {
const [name, setName] = useState('');
const [errors, setErrors] = useState({});
const handleSubmit = (event) => {
event.preventDefault();
if (!name) {
setErrors({ name: 'Name is required' });
return;
}
alert('Name submitted: ' + name);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
{errors.name && <span>{errors.name}</span>}
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ValidationForm;
When there are multiple input elements, handling them separately can be cumbersome. Instead, you can handle multiple inputs using a single `handleChange` handler.
import React, { useState } from 'react';
function MultiInputForm() {
const [formState, setFormState] = useState({
firstName: '',
lastName: '',
email: ''
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormState(prevState => ({ ...prevState, [name]: value }));
};
const handleSubmit = (event) => {
event.preventDefault();
alert('Form submitted: ' + JSON.stringify(formState));
};
return (
<form onSubmit={handleSubmit}>
<label>
First Name:
<input
type="text"
name="firstName"
value={formState.firstName}
onChange={handleChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={formState.lastName}
onChange={handleChange}
/>
</label>
<label>
Email:
<input
type="email"
name="email"
value={formState.email}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default MultiInputForm;
Handling forms with dynamic fields, like when users can add or remove fields, can be challenging. One common scenario is handling an array of inputs.
import React, { useState } from 'react';
function ArrayForm() {
const [names, setNames] = useState(['']);
const handleChange = (index, event) => {
const newNames = [...names];
newNames[index] = event.target.value;
setNames(newNames);
};
const handleAddField = () => {
setNames([...names, '']);
};
const handleRemoveField = (index) => {
const newNames = [...names];
newNames.splice(index, 1);
setNames(newNames);
};
const handleSubmit = (event) => {
event.preventDefault();
alert('Names submitted: ' + names.join(', '));
};
return (
<form onSubmit={handleSubmit}>
{names.map((name, index) => (
<div key={index}>
<input
type="text"
value={name}
onChange={(event) => handleChange(index, event)}
/>
<button type="button" onClick={() => handleRemoveField(index)}>Remove</button>
</div>
))}
<button type="button" onClick={handleAddField}>Add Field</button>
<button type="submit">Submit</button>
</form>
);
}
export default ArrayForm;
For more complex forms, using a form library like Formik or React Hook Form can be beneficial. These libraries provide enhanced functionalities like form state management, validation, and error handling. Here is an example using Formik:
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
function FormikForm() {
return (
<Formik
initialValues={{ name: '' }}
validate={(values) => {
const errors = {};
if (!values.name) errors.name = 'Name is required';
return errors;
}}
onSubmit={(values) => {
alert('Name submitted: ' + values.name);
}}
>
{() => (
<Form>
<label>
Name:
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
</label>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
);
}
export default FormikForm;
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here