Skip to Content

How to Create and Process Forms in React

React is a widely used JavaScript library for creating user interfaces, especially for single-page applications. One of the essential aspects of any web application is form handling, which involves creating, validating, and processing forms. This guide will take you through building and managing forms in React, from the basics to more advanced techniques.

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

Setting Up Your Environment

Before creating forms in React, ensure you have a React development environment set up. You can use Create React App to bootstrap a new React project quickly. These command prompts will create a new React project and start the development server.

# npx create-react-app forms
# cd forms
# npm start

Basic Form Creation

Creating a basic form in React involves using standard HTML form elements within a React component. Here’s a simple example of a form with text input and a submit button. When the form is submitted, the handleSubmit function is called and displays the user-generated name in an alert box.

import React, { useState } from 'react';

function BasicForm() {
const [name, setName] = useState('');

const handleSubmit = (event) => {
event.preventDefault();
alert("Form submitted with name: ${name}");
};

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

export default BasicForm;

Managing Form State

Managing state is crucial in React applications, especially for forms. Use React’s useState hook to handle form data. In this example, we'll deal with multiple form inputs and single-state objects, making form management easy.

import React, { useState } from 'react';

function MultiInputForm() {
const [formData, setFormData] = useState({
firstName: '',
lastName: '',
email: ''
});

const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};

const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted: ${JSON.stringify(formData)}`);
};

return (
<form onSubmit={handleSubmit}>
<label>
First Name:
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleChange}
/>
</label>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}

export default MultiInputForm;

Form Validation

Form validation ensures that user inputs meet specific criteria before submission. React doesn't provide built-in form validation, but you can implement it using state and custom functions.

Here's an example of basic form validation by checking for a valid user-generated email address:

import React, { useState } from 'react';

function ValidatedForm() {
const [formData, setFormData] = useState({ email: '' });
const [errors, setErrors] = useState({});

const validate = () => {
const errors = {};
if (!formData.email.includes('@')) {
errors.email = 'Invalid email address';
}
return errors;
};

const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};

const handleSubmit = (event) => {
event.preventDefault();
const errors = validate();
if (Object.keys(errors).length === 0) {
alert('Form submitted successfully');
} else {
setErrors(errors);
}
};

return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</label>
<button type="submit">Submit</button>
</form>
);
}

export default ValidatedForm;

Handling Form Submission

Handling form submission in React typically involves preventing the default form submission behavior and performing some action, such as sending data to a server.

When sending data to a server, you can use the fetch API or a library like axios. In this example, we'll use the latter so you can see how different libraries perform.

First, install the axios dependencies in your project:

# npm install axios

Now, use this code as an example to process your form:

import React, { useState } from 'react';
import axios from 'axios';

function SubmitForm() {
const [formData, setFormData] = useState({ name: '', email: '' });

const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};

const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('/api/submit', formData);
alert(`Form submitted successfully: ${response.data}`);
} catch (error) {
alert(`Error submitting form: ${error}`);
}
};

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

export default SubmitForm;

Advanced Form Handling

For more advanced form handling, consider using a library like Formik or React Hook Form, which simplifies form management and validation.

Using Formik

Formik is a popular form library for React that provides a higher-level API for managing form state and validation. We'll also use Yup, a JavaScript library that allows you to create object schemas for your data. With Yup, you can validate your data to ensure it adheres to these schemas or transform your data to fit them. A Yup schema specifies the structure and expected types of values for your data.

Make sure to install these dependencies first:

# npm install formik
# npm install yup

Now you can copy the code to your project and run:

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

const SignupForm = () => {
const initialValues = { name: '', email: '' };
const validationSchema = Yup.object({
name: Yup.string().required('Required'),
email: Yup.string().email('Invalid email address').required('Required')
});

const handleSubmit = (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
};

return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}>
{({ isSubmitting }) => (
<Form>
<label>
Name:
<Field type="text" name="name" />
<ErrorMessage name="name" component="div" />
</label>
<label>
Email:
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />
</label>
<button type="submit" disabled={isSubmitting}>Submit</button>
</Form>
)}
</Formik>
);
};

export default SignupForm;

Using React Hook Form

React Hook Form is another library that leverages React Hooks for form management and validation, offering excellent performance and ease of use.

Make sure to install the dependency first:

# npm install react-hook-form

Now you can copy the code to your project and run:

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

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

const onSubmit = (data) => {
alert(JSON.stringify(data));
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
Name:
<input {...register('name', { required: 'Name is required' })} />
{errors.name && <p>{errors.name.message}</p>}
</label>
<label>
Email:
<input
{...register('email', {
required: 'Email is required',
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Invalid email address'
}
})}
/>
{errors.email && <p>{errors.email.message}</p>}
</label>
<button type="submit">Submit</button>
</form>
);
}

export default HookForm;

Conclusion

Handling forms is a fundamental part of web development, and React offers several ways to manage form state, validation, and submission. You can build robust and user-friendly forms in your React applications by understanding the basics and exploring advanced techniques.

Whether you prefer the simplicity of React’s built-in hooks or the power of libraries like Formik and React Hook Form, mastering form handling in React will enhance your development skills and improve your application’s user experience.

Posted by: Josh Rowe
Created: May 22, 2024

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.