React Form allow for handling user input and managing form submission. React provides controlled and uncontrolled components for handling forms.
1. Controlled Components
In controlled components, form data is handled by the component’s state.
Functional Components with Hooks
import React, { useState } from 'react';
export default function MyForm() {
const [name, setName] = useState('');
const [age, setAge] = useState('');
const handleNameChange = (event) => {
setName(event.target.value);
};
const handleAgeChange = (event) => {
setAge(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Name: ${name}, Age: ${age}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleNameChange} />
</label>
<br />
<label>
Age:
<input type="number" value={age} onChange={handleAgeChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
2. Uncontrolled Components
In uncontrolled components, form data is handled by the DOM itself.
Using ref in Functional Components
import React, { useRef } from 'react';
export default function MyForm() {
const nameRef = useRef(null);
const ageRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
alert(`Name: ${nameRef.current.value}, Age: ${ageRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={nameRef} />
</label>
<br />
<label>
Age:
<input type="number" ref={ageRef} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
Handling Form Validation
Form validation can be added by checking the form data before submission.
Functional Components with Hooks
import React, { useState } from 'react';
export default function MyForm() {
const [formState, setFormState] = useState({ name: '', age: '' });
const [errors, setErrors] = useState({ name: '', age: '' });
const handleChange = (event) => {
const { name, value } = event.target;
setFormState((prevState) => ({
...prevState,
[name]: value,
}));
};
const validateForm = () => {
let valid = true;
let errors = {};
if (!formState.name) {
valid = false;
errors.name = 'Name is required';
}
if (!formState.age) {
valid = false;
errors.age = 'Age is required';
} else if (isNaN(formState.age)) {
valid = false;
errors.age = 'Age must be a number';
}
setErrors(errors);
return valid;
};
const handleSubmit = (event) => {
event.preventDefault();
if (validateForm()) {
alert(`Name: ${formState.name}, Age: ${formState.age}`);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" value={formState.name} onChange={handleChange} />
{errors.name && <span>{errors.name}</span>}
</label>
<br />
<label>
Age:
<input type="number" name="age" value={formState.age} onChange={handleChange} />
{errors.age && <span>{errors.age}</span>}
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
create form through use react-hook-form library
install react-hook-form
npm install react-hook-form
create form through react-hook-form with validation
import React from 'react';
import { useForm } from 'react-hook-form';
export default function SignUp(){
const {register,handleSubmit,formState: { errors }} = useForm();
const signupSubmit = async (data) =>{
console.log(data);
}
return(
<div>
<h1>Signup Form</h1>
<form onSubmit={handleSubmit(signupSubmit)}>
<div className='container'>
<div className="row">
FirstName:
<input type="text" id="firstName" {...register('firstName',{required:{value:true,message:"First Name is required"},maxLength:{value:10, message:"First Name should be less than or equal to 10"}})} />
{errors.firstName && <p className='alert alert-danger'>{errors.firstName?.message}</p> }
</div>
<div className="row my-2">
LastName:
<input type="text" id="lastName" {...register('lastName',{required:{value:true,message:"Last Name is required"},maxLength:{value:10, message:"Last Name should be less than or equal to 10"}})} />
{errors.lastName && <p className='alert alert-danger'>{errors.lastName?.message}</p> }
</div>
<div><button className='btn btn-primary'>Submit</button></div>
</div>
</form>
</div>
)
}
React Form – Interview Questions
Q 1: What is a form in React?
Ans: A React form is used to collect and manage user input.
Q 2: What is a controlled component?
Ans: A component where form data is handled by React state.
Q 3: How do you handle form submission in React?
Ans: Using the onSubmit event handler.
Q 4: Why are controlled components preferred?
Ans: They provide better control and validation of input data.
Q 5: Can multiple inputs be handled with one handler?
Ans: Yes, using the name attribute and dynamic state updates.
Reactjs React Form – Objective Questions (MCQs)
Q1. What is a form in React?
Q2. How do you access form input values in React Functional Components?
Q3. What is a controlled component in React forms?
Q4. How do you handle form submission in React?
Q5. What is the difference between controlled and uncontrolled components in React forms?