Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

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.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz