21. How do you handle forms in React?

Handling forms in React involves managing form state and validation. This can be done using either controlled or uncontrolled components. Controlled components are more common as they provide full control over the form data.

Example of a controlled component:

import React, { useState } from 'react'; function MyForm() { const [values, setValues] = useState({ name: '', email: '' }); const handleChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value }); }; const handleSubmit = (e) => { e.preventDefault(); // Validation and form data submission console.log(values); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" name="name" value={values.name} onChange={handleChange} /> </label> <label> Email: <input type="email" name="email" value={values.email} onChange={handleChange} /> </label> <button type="submit">Submit</button> </form> ); }

Example of an uncontrolled component:

import React, { useRef } from 'react'; function MyForm() { const nameRef = useRef(null); const emailRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); console.log({ name: nameRef.current.value, email: emailRef.current.value }); }; return ( <form onSubmit={handleSubmit}> <label> Name: <input type="text" ref={nameRef} /> </label> <label> Email: <input type="email" ref={emailRef} /> </label> <button type="submit">Submit</button> </form> ); }

Handling forms in React allows for dynamic management of user data and validation before submission to the server.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.