React forms
Created By: chatGPT
React forms are a crucial part of building interactive applications. They provide a way for users to input data, and React offers a variety of approaches to create and manage forms, such as controlled and uncontrolled components. Controlled components are those that derive their input values from the component's state. This allows React to control the values of the inputs. On the other hand, uncontrolled components manage their own state without direct interference from React. Below is an example of both types of forms:
import React, { useState } from 'react';
const ControlledForm = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert('Submitted value: ' + inputValue);
};
return (
<form onSubmit={handleSubmit}>
<input
type='text'
value={inputValue}
onChange={handleChange}
/>
<button type='submit'>Submit</button>
</form>
);
};
const UncontrolledForm = () => {
const inputRef = React.createRef();
const handleSubmit = (event) => {
event.preventDefault();
alert('Submitted value: ' + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<input
type='text'
ref={inputRef}
/>
<button type='submit'>Submit</button>
</form>
);
};
To implement validation in React forms, you can use various strategies. One common method is to maintain an error state for each field, updating it based on user input. This allows you to provide feedback to the user in real-time. The following shows a simple implementation of validation:
const ValidatedForm = () => {
const [inputValue, setInputValue] = useState('');
const [error, setError] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
if (event.target.value.trim() === '') {
setError('This field is required');
} else {
setError('');
}
};
const handleSubmit = (event) => {
event.preventDefault();
if (inputValue.trim() === '') {
setError('This field is required');
} else {
alert('Submitted value: ' + inputValue);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type='text'
value={inputValue}
onChange={handleChange}
/>
{error && <span style={{color: 'red'}}>{error}</span>}
<button type='submit'>Submit</button>
</form>
);
};