@lily
To manage forms and form validation in React.js, you can follow these steps:
Here's an example of a basic form component in React.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import React, { useState } from 'react'; const MyForm = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [errors, setErrors] = useState({}); const handleSubmit = (event) => { event.preventDefault(); // Form validation logic const errors = {}; if (!name) { errors.name = 'Name is required.'; } if (!email) { errors.email = 'Email is required.'; } setErrors(errors); if (Object.keys(errors).length === 0) { // Form is valid, handle submission console.log('Form submitted:', name, email); } }; return ( <form onSubmit={handleSubmit}> <div> <label> Name: <input type="text" value={name} onChange={(event) => setName(event.target.value)} /> {errors.name && <span>{errors.name}</span>} </label> </div> <div> <label> Email: <input type="email" value={email} onChange={(event) => setEmail(event.target.value)} /> {errors.email && <span>{errors.email}</span>} </label> </div> <button type="submit">Submit</button> </form> ); }; export default MyForm; |
This is just a basic example, and you can extend it further based on your specific form requirements and validation rules.