React Forms
How do you handle forms in React?
In React, forms are handled by controlling the input elements through the component's state. Each form field is controlled by linking its value to the component's state, and updates to the form are handled through event listeners, typically on the onChange
event. This is known as a controlled component approach.
Example of handling a simple form:
import React, { useState } from 'react';
function FormExample() {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted with:', inputValue);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={inputValue} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, the input field's value is controlled by React state, and updates to the field are handled using the handleChange
function. The form's submission is prevented with preventDefault()
to handle it manually in React.
What is a controlled component in React?
A controlled component is a form element whose value is controlled by React through the component's state. The form element's value is set using the value
attribute, and the input changes are handled by updating the state using the onChange
event handler. The state in the component is the "single source of truth" for the form element's value.
Example of a controlled component:
function ControlledInput() {
const [text, setText] = useState('');
const handleChange = (event) => {
setText(event.target.value); // Update state on input change
};
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>Current value: {text}</p>
</div>
);
}
In this example, the value of the input field is controlled by the React state, and any changes to the input field are reflected by updating the state.
What is an uncontrolled component in React?
An uncontrolled component is a form element that manages its own internal state. Instead of controlling the value of the form element via React state, you use the DOM to retrieve its value using a reference (via ref
). In uncontrolled components, React does not directly manage the input value, and the value is accessed using refs
when needed.
Example of an uncontrolled component:
import React, { useRef } from 'react';
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
console.log('Input value:', inputRef.current.value); // Access value from the DOM
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputRef} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, the input field is not controlled by React's state. Instead, its value is accessed directly using a ref
when the form is submitted.
What are the differences between controlled and uncontrolled components in React?
Key differences between controlled and uncontrolled components in React:
- Controlled components: The form element's value is controlled by React state. The input value is set using the
value
attribute, and changes are handled using anonChange
handler. - Uncontrolled components: The form element's value is managed by the DOM, and the value is accessed using
ref
. React doesn't control the input state, and you get the value only when needed (e.g., during form submission). - Controlled components provide more control: Controlled components allow for better form validation, conditional formatting, and real-time updates to the UI based on the input value, while uncontrolled components are simpler and require less code.
How do you handle multiple form inputs in React?
In forms with multiple inputs, you can manage each input field's state using a single state object and update the specific field using the name
attribute of the input element. You can create a generic handleChange
function to update the state based on the name
of the input field.
Example of handling multiple inputs:
function MultiInputForm() {
const [formData, setFormData] = useState({
name: '',
email: ''
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form data:', 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>
);
}
In this example, a single state object formData
is used to manage multiple inputs, and the handleChange
function updates the state dynamically based on the name
attribute of the input.
How do you handle form submission in React?
In React, form submission is handled by preventing the default behavior of the form using event.preventDefault()
in the form's onSubmit
event handler. This allows you to handle form data in your component before sending it to the server or performing other actions.
Example of handling form submission:
function SimpleForm() {
const [inputValue, setInputValue] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted with:', inputValue);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, form submission is handled by preventing the default page refresh and logging the input value when the form is submitted.
How can you implement form validation in React?
Form validation in React can be implemented by checking the input fields for validity and updating the state or displaying error messages accordingly. You can add custom validation logic inside the handleSubmit
function or inside the handleChange
function.
Example of implementing form validation:
function FormWithValidation() {
const [formData, setFormData] = useState({ email: '' });
const [errors, setErrors] = useState({ email: '' });
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({ [name]: value });
// Simple validation
if (name === 'email' && !value.includes('@')) {
setErrors({ email: 'Invalid email address' });
} else {
setErrors({ email: '' });
}
};
const handleSubmit = (event) => {
event.preventDefault();
if (!formData.email) {
console.log('Please enter a valid email.');
} else {
console.log('Form submitted with:', formData);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" name="email" value={formData.email} onChange={handleChange} />
<p style={{ color: 'red' }}>{errors.email}</p>
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, the email field is validated to ensure it contains an "@" symbol. If it doesn't, an error message is displayed, and the form cannot be submitted with invalid data.
How do you handle checkbox inputs in React forms?
Handling checkbox inputs in React is similar to handling text inputs, but instead of tracking the text value, you track the checkbox's checked state using the checked
property in the state.
Example of handling checkbox inputs:
function CheckboxExample() {
const [isChecked, setIsChecked] = useState(false);
const handleChange = (event) => {
setIsChecked(event.target.checked);
};
return (
<div>
<label>
Accept Terms:
<input type="checkbox" checked={isChecked} onChange={handleChange} />
</label>
<p>Checkbox is {isChecked ? 'checked' : 'unchecked'}</p>
</div>
);
}
In this example, the checked
property is controlled by React state, and the checkbox's state is updated whenever it is toggled.