Forms in ReactJS
✅ Forms in ReactJS
In ReactJS, forms are used to collect input from users. Unlike traditional HTML forms, React uses controlled components where form elements are controlled by React state.
📌 1. Controlled Components
A controlled component is a form element whose value is managed by React state using useState.
Example: Simple Form with Controlled Input
<form> import React, { useState } from 'react';const FormValidation = () => { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const handleChange = (e) => { setEmail(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); if (!email.includes('@')) { setError('Invalid Email!'); } else { setError(''); alert(`Valid Email: ${email}`); } }; <form onSubmit={handleSubmit}> <label> Email: <input type="email" value={email} onChange={handleChange} /> </label> {error && <p style={{ color: 'red' }}>{error}</p>} <button type="submit">Submit</button> </form> );};export default FormValidation;
Validation Logic → Checks if email contains
@.Error Message → Displayed using conditional rendering.
✅ Final Thoughts
Use controlled components for form management using
useState.Handle form submission using
onSubmit.Apply form validation for better user experience.
Use
onChangefor capturing input values.