A controlled input in React is an input element whose value is controlled by the state of the component.
const [value, setValue] = useState(''); const handleChange = (e) => { setValue(e.target.value); }; return ( <input type="text" value={value} onChange={handleChange} /> );
A controlled `<textarea>` works similarly to an input, where its value is managed by the component's state.
const [text, setText] = useState(''); const handleTextChange = (e) => { setText(e.target.value); }; return ( <textarea value={text} onChange={handleTextChange} /> );
The `onSubmit` event handler is used to capture form submissions and prevent the default action.
const handleSubmit = (e) => { e.preventDefault(); console.log("Form submitted!"); }; return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> );
You can use `useState` to track form field values and submit them with a single state object.
const [formData, setFormData] = useState({ name: '', email: '', }); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value, }); }; const handleSubmit = (e) => { e.preventDefault(); console.log(formData); }; return ( <form onSubmit={handleSubmit}> <input type="text" name="name" value={formData.name} onChange={handleChange} /> <input type="email" name="email" value={formData.email} onChange={handleChange} /> <button type="submit">Submit</button> </form> );
Use the `required` attribute on form fields to enforce basic validation.
<form> <input type="text" required /> <button type="submit">Submit</button> </form>
You can implement custom validation using `useState` and `useEffect` to manage validation rules.
const [formData, setFormData] = useState({ name: '' }); const [errors, setErrors] = useState({}); const handleSubmit = (e) => { e.preventDefault(); if (!formData.name) { setErrors({ name: 'Name is required' }); } else { console.log(formData); } }; return ( <form onSubmit={handleSubmit}> <input type="text" name="name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} /> {errors.name && <span>{errors.name}</span>} <button type="submit">Submit</button> </form> );
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!