Working with
Forms
Controlled component
• Controlled components in React are the components
whose state and behaviors are managed by React
components using states
• In a controlled component, form data is handled by the
React component state.
• Every input element (like a text box, select dropdown,
etc.) has its value controlled by the component’s state.
• The component directly manages the input’s value
through the value attribute, and any changes are handled
by event handlers like onChange.
example
import React, { useState } from 'react';
function Controlled() {
const [inputValue, setInputValue] = useState("");
const handleChange = (e) => {
setInputValue(e.target.value);
// Update state on change
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submitted Value:", inputValue);
};
const a=()=>{
alert("form succesfullly submitted")
}
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={inputValue} // Controlled by state
onChange={handleChange} // Handler to update state
/>
</label>
<button type="submit" onClick={a}>Submit</button>
</form>
);
e.preventDefault():
This prevents the default action of the form, which would
normally cause the page to reload when the form is
submitted.
This is necessary in React (or any JavaScript-driven form
handling) because you typically want to handle the
submission yourself, without causing a full page refresh.
Uncontrolled component
• Uncontrolled Components are the components that do not
handle by React
• This component handle by DOM
• The React component doesn’t manage or store the
current value of the form fields. Instead, you access the
value only when you need it, typically using refs.
• The input value is managed by the DOM and is retrieved
via JavaScript when necessary.
import React, { useRef } from 'react';
function Uncontrolled() {
const inputRef = useRef(null); // Create a ref
const handleSubmit = (e) => {
e.preventDefault();
console.log("Submitted Value:", inputRef.current.value); // Access the input value via ref
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
ref={inputRef} // Uncontrolled, value managed by the DOM
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default Uncontrolled;
form and form validation
import React, { useState } from "react";
import './Formvalidation.css';
const Formvalidation = () => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
confirmPassword: ''
})
const [errors, setErrors] = useState({})
const handleChange = (e) => {
const {name, value} = e.target;
setFormData({
...formData, [name] : value
})
}
const handleSubmit = (e) => {
e.preventDefault()
const validationErrors = {}
if(!formData.username.trim()) {
validationErrors.username = "username is required"
}
if(!formData.email.trim()) {
validationErrors.email = "email is required"
} else if(!/\S+@\S+\.\S+/.test(formData.email)){
validationErrors.email = "email is not valid"
}
if(!formData.password.trim()) {
validationErrors.password = "password is required"
} else if(formData.password.length < 6){
validationErrors.password = "password should be at least 6 char"
}
if(formData.confirmPassword !== formData.password) {
validationErrors.confirmPassword = "password not matched"
}
setErrors(validationErrors)
if(Object.keys(validationErrors).length === 0) {
alert("Form Submitted successfully")
}
}
return(
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input
type="text"
name="username"
placeholder='username'
value={formData.username}
onChange={handleChange}
/>
{errors.username && <span>{errors.username}</span>}
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
placeholder='example@gmail.com'
value={formData.email}
onChange={handleChange}
/>
{errors.email && <span>{errors.email}</span>}
</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
<div>
<label>Confirm Password:</label>
<input
type="password"
name="confirmPassword"
placeholder='******'
value={formData.confirmPassword}
onChange={handleChange}
/>
{errors.confirmPassword && <span>{errors.confirmPassword}</span>}
</div>
<button type="submit">Submit</button>
</form>
)
};
export default Formvalidation;