Forms – React

Forms in React are essential for collecting user input and managing state. React provides several ways to create and manage forms, including controlled components, uncontrolled components, form libraries, and custom hooks. Here’s a comprehensive guide to understanding forms in React.

1. Controlled Components

Controlled components are form elements whose values are managed by the React state. This approach gives you full control over the form’s data.

Example:

import React, { useState } from 'react';

function ControlledForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');

const handleSubmit = (event) => {
event.preventDefault();
console.log(`Name: ${name}, Email: ${email}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
</label>
<br />
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

2. Uncontrolled Components

Uncontrolled components are form elements that handle their own state internally, without syncing with the React state. This approach uses refs to access form values.

Example:

import React, { useRef } from 'react';

function UncontrolledForm() {
const nameRef = useRef();
const emailRef = useRef();

const handleSubmit = (event) => {
event.preventDefault();
console.log(`Name: ${nameRef.current.value}, Email: ${emailRef.current.value}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={nameRef} />
</label>
<br />
<label>
Email:
<input type="email" ref={emailRef} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

3. Form Validation

Form validation is crucial for ensuring data integrity. You can implement validation in controlled components using custom logic.

Example:

import React, { useState } from 'react';

function FormWithValidation() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [errors, setErrors] = useState({});

const validate = () => {
const newErrors = {};
if (!name) newErrors.name = 'Name is required';
if (!email) newErrors.email = 'Email is required';
else if (!/\S+@\S+\.\S+/.test(email)) newErrors.email = 'Email is invalid';
return newErrors;
};

const handleSubmit = (event) => {
event.preventDefault();
const formErrors = validate();
if (Object.keys(formErrors).length > 0) {
setErrors(formErrors);
} else {
console.log(`Name: ${name}, Email: ${email}`);
// Reset form
setName('');
setEmail('');
setErrors({});
}
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
{errors.name && <span style={{ color: 'red' }}>{errors.name}</span>}
</label>
<br />
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
{errors.email && <span style={{ color: 'red' }}>{errors.email}</span>}
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

4. Handling Multiple Inputs

Handling multiple inputs in controlled components can be streamlined using a single state object and a dynamic onChange handler.

Example:

import React, { useState } from 'react';

function MultipleInputsForm() {
const [formValues, setFormValues] = useState({
name: '',
email: '',
age: '',
});

const handleChange = (e) => {
const { name, value } = e.target;
setFormValues({
...formValues,
[name]: value,
});
};

const handleSubmit = (event) => {
event.preventDefault();
console.log(formValues);
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" value={formValues.name} onChange={handleChange} />
</label>
<br />
<label>
Email:
<input type="email" name="email" value={formValues.email} onChange={handleChange} />
</label>
<br />
<label>
Age:
<input type="number" name="age" value={formValues.age} onChange={handleChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

5. Using Form Libraries

React form libraries like Formik and React Hook Form can simplify form management, validation, and submission.

Formik Example:

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

function FormikForm() {
return (
<Formik
initialValues={{ name: '', email: '' }}
validationSchema={Yup.object({
name: Yup.string().required('Name is required'),
email: Yup.string().email('Invalid email address').required('Email is required'),
})}
onSubmit={(values, { setSubmitting }) => {
console.log(values);
setSubmitting(false);
}}
>
<Form>
<label>
Name:
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" style={{ color: 'red' }} />
</label>
<br />
<label>
Email:
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" style={{ color: 'red' }} />
</label>
<br />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}

React Hook Form Example:

import React from 'react';
import { useForm } from 'react-hook-form';

function HookForm() {
const { register, handleSubmit, formState: { errors } } = useForm();

const onSubmit = (data) => {
console.log(data);
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
Name:
<input {...register('name', { required: 'Name is required' })} />
{errors.name && <span style={{ color: 'red' }}>{errors.name.message}</span>}
</label>
<br />
<label>
Email:
<input {...register('email', { required: 'Email is required', pattern: /\S+@\S+\.\S+/ })} />
{errors.email && <span style={{ color: 'red' }}>{errors.email.message}</span>}
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

6. Custom Hooks for Form Handling

Creating custom hooks can further encapsulate form logic and promote reusability.

Example:

import React, { useState } from 'react';

function useForm(initialValues) {
const [values, setValues] = useState(initialValues);

const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};

const handleSubmit = (callback) => (e) => {
e.preventDefault();
callback(values);
};

return {
values,
handleChange,
handleSubmit,
};
}

function CustomHookForm() {
const { values, handleChange, handleSubmit } = useForm({ name: '', email: '' });

const submitForm = (formValues) => {
console.log(formValues);
};

return (
<form onSubmit={handleSubmit(submitForm)}>
<label>
Name:
<input type="text" name="name" value={values.name} onChange={handleChange} />
</label>
<br />
<label>
Email:
<input type="email" name="email" value={values.email} onChange={handleChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

Conclusion

Forms in React can be managed using various approaches, from controlled and uncontrolled components to using libraries like Formik and React Hook Form. Understanding these different methods allows you to choose the best solution for your specific use case, ensuring efficient and effective form management in your React applications.

Tags: No tags

One Response

Leave a Reply to Ambika Amar Maka Cancel reply

Your email address will not be published. Required fields are marked *