Form In React
Forms are a fundamental part of web applications, enabling users to input and submit data. In React, handling forms is slightly different from traditional HTML due to React's component-based architecture and state management. This article will provide a comprehensive guide to creating and managing forms in React, covering controlled and uncontrolled components, form validation, and best practices.
In React, forms can be managed in two primary ways:
- Controlled Components: Form elements are controlled by React's state.
- Uncontrolled Components: Form elements maintain their own state, and React accesses their values using refs.
1. Controlled Components
In controlled components, the form data is handled by the React component's state. This approach provides more control over the form elements and their values.
Example of a Controlled Form:
import React, { useState } from "react";
function ControlledForm() {
const [formData, setFormData] = useState({
name:"",
email:"",
});
const handleChange= (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]:value,
}));
};
const handleSubmit= (e) => {
e.preventDefault();
console.log("Form Submitted:", formData);
};
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 ControlledForm;
Key Points:
- The
valueof each input is tied to the component's state. - The
onChangehandler updates the state whenever the input value changes. - The
onSubmithandler prevents the default form submission and processes the data.
2. Uncontrolled Components
In uncontrolled components, the form data is managed by the DOM itself, and React accesses the values using refs. This approach is useful for simple forms or when you need to integrate with non-React code.
Example of an Uncontrolled Form:
import React, { useRef } from "react";
function UncontrolledForm() {
const nameRef = useRef();
const emailRef = useRef();
const handleSubmit= (e) => {
e.preventDefault();
console.log("Name:", nameRef.current.value);
console.log("Email:", emailRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={nameRef}/>
</label>
<br/>
<label>
Email:
<input type="email" ref={emailRef}/>
</label>
<br/>
<button type="submit">Submit</button>
</form>
);
}
export default UncontrolledForm;
Key Points:
- The
refattribute is used to access the DOM elements directly. - The form values are retrieved using
ref.current.value.
3. Handling Form Validation
Form validation ensures that the user inputs meet specific criteria before submission. Validation can be implemented using JavaScript or third-party libraries like Formik or React Hook Form.
Example of Basic Validation:
import React, { useState } from "react";
function FormWithValidation() {
const [formData, setFormData] = useState({ email:"" });
const [error, setError] = useState("");
const handleChange = (e) => {
setFormData({ email:e.target.value });
};
const handleSubmit= (e) => {
e.preventDefault();
if (!formData.email.includes("@")) {
setError("Invalid email address");
} else {
setError("");
console.log("Form Submitted:", formData);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input
type="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br/>
{error && <p style={{ color:"red" }}>{error}</p>}
<button type="submit">Submit</button>
</form>
);
}
export default FormWithValidation;
