• Articles
  • Tutorials
  • Interview Questions

How to Build Forms in React?

How to Build Forms in React?

With React’s component-based architecture and state management system, developers can create dynamic and interactive forms that respond to user input in real-time. In this blog, we’ll embark on an exciting journey into the realm of building forms in React, where creativity meets technical prowess. Get ready to dive into the world of React Forms, where innovation meets practicality and the possibilities are boundless.

Table of Contents

Learn all about React through this React JS Course video:

Video Thumbnail

What are React Forms?

React forms are an essential part of building interactive web applications. They allow users to input and submit data. It can then be processed and used within the application. In React, forms are created using components that handle user input and manage the state of form data.

Setting Up a React Project

Before diving into creating forms in React, it’s important to set up a React project. There are multiple ways to set up a React project, but one common approach is to use Create React App (CRA). CRA provides a boilerplate setup with a preconfigured development environment, making it quick and easy to start building React applications.

You can use CRA to create a React project by following these steps:

  1. Navigate to the desired location where you want to create your project by opening your terminal or command prompt.
  1. To create a new React app, execute the command below:
npx create-react-app my-app

Change “my-app” to the project’s preferred name.

  1. After the command has finished, go to the project directory:
cd my-app

Get the knowledge you need to implement React in real world scenarios through our React JS Course.

Basic Form Elements

Basic Form Elements

Several built-in components are available in React to manage form elements. Let’s look at some of the important ones:

Input Fields

Users can enter text or numeric values in input fields. To construct input fields in React, use the <input> element with a variety of types, including text, number, email, etc. Here is an illustration of a fundamental React text input field component:

import React, { useState } from 'react';

const TextInput = () => {
  const [value, setValue] = useState('');

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return (
    <input
      type="text"
      value={value}
      onChange={handleChange}
    />
  );
};

export default TextInput;

In this example, the value of the input field is stored in the state using the useState hook. The handleChange function updates the state whenever the input value changes.

Get 100% Hike!

Master Most in Demand Skills Now!

Textareas

Textareas are used for multiline text input. In React, you can use the <textarea> element to create textareas. Here’s an example:

import React, { useState } from 'react';
const TextArea = () => {
  const [value, setValue] = useState('');
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  return (
    <textarea
      value={value}
      onChange={handleChange}
    />
  );
};
export default TextArea;

Similar to the input field example, the value of the textarea is stored in the state using useState, and the handleChange function updates the state when the textarea value changes.

Select Menus

Select menus, also known as dropdowns or dropdown menus, allow users to choose an option from a list. In React, you can use the <select> element along with <option> elements to create select menus. Here’s an example:

import React, { useState } from 'react';
const SelectMenu = () => {
  const [selectedOption, setSelectedOption] = useState('');
  const handleChange = (e) => {
    setSelectedOption(e.target.value);
  };
  return (
    <select value={selectedOption} onChange={handleChange}>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>
    </select>
  );
};
export default SelectMenu;

In this example, the selected option is stored in the state using useState, and the handleChange function updates the state when a different option is selected.

Get your React JS basics clear through our React JS Tutorial.

Handling Form Submissions

When building a React app, handling form submissions is a common requirement. It involves capturing user input from form fields and processing it in some way, such as submitting data to a server or updating the application state.

To handle form submissions in React, developers start with defining a form component that encapsulates the form fields and handles the submission logic. Moreover, you can apply the form element as well as its related input elements, such as input, select, and textarea to create the form structure.

Form Validation

Form validation is crucial to ensuring that the data submitted by users meet certain criteria or constraints. It helps prevent erroneous or incomplete data from being processed and provides a better user experience by providing immediate feedback.

There are two main types of form validation: client-side validation and server-side validation.

Client-Side Validation

Client-side validation is performed in the user’s browser using JavaScript before the form is submitted. It allows for instant feedback to the user without making a server request. Common validation checks include required fields, email format, password strength, and input length.

Example of client-side validation using React:

import React, { useState } from 'react';
const MyForm = () => {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');
  const handleInputChange = (e) => {
    setEmail(e.target.value);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    if (!email) {
      setError('Please enter an email address.');
      return;
    }
    // Process the form submission
    // ...
  };
  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} onChange={handleInputChange} />
      {error && <p>{error}</p>}
      <button type="submit">Submit</button>
    </form>
  );
};
export default MyForm;

In this example, the form has an input field for email and a submit button. The handleInputChange function updates the email state as the user types. On form submission, the handleSubmit function checks if the email is empty and displays an error message if it is.

Server-Side Validation

Server-side validation is performed on the server after the form is submitted. It provides an additional layer of security and validation to ensure the submitted data is valid and meets the server’s requirements. Server-side validation is essential, as client-side validation can be bypassed.

Prepare for your React Interview properly by going through the most asked React Interview Questions.

Managing Form State

Managing Form State

Effectively managing the form state is a crucial aspect of working with forms in React. This involves keeping track of the form field values, any validation errors, and the overall validity of the form.

There are two common approaches to managing form states: controlled components and uncontrolled components.

Controlled Components

In controlled components, the form state is managed by React. Each form field has a corresponding state value, and changes to the field are reflected in the state and vice versa. This allows for full control and synchronization between the form fields and the component’s state.

Example of a controlled component:

import React, { useState } from 'react';
const MyForm = () => {
  const [name, setName] = useState('');
  const handleInputChange = (e) => {
    setName(e.target.value);
  };
  return (
    <form>
      <input type="text" value={name} onChange={handleInputChange} />
    </form>
  );
};
export default MyForm;

In this particular case, the input field’s value is set to the name state, and any changes made to the input value are reflected in the name state through the handleInputChange function.

Uncontrolled Components

In uncontrolled components, the form fields maintain their own state, and React does not control it. Instead, you can access the field values using a ref or by accessing the DOM directly. Uncontrolled components are useful for simple forms or when you need more control over form behavior.

Example of an uncontrolled component:

import React, { useRef } from 'react';
const MyForm = () => {
  const nameInputRef = useRef();
  const handleSubmit = (e) => {
    e.preventDefault();
    const name = nameInputRef.current.value;
    // Process the form submission
    // ...
  };
  return (
   <form onSubmit={handleSubmit}>
      <input type="text" ref={nameInputRef} />
      <button type="submit">Submit</button>
    </form>
  );
};
export default MyForm;

In this specific instance, the nameInputRef is used to obtain the input field’s value upon form submission.

Go through these Android Interview Questions to excel in your interview.

Handling User Input

Handling user input is a fundamental aspect of building forms in React. React provides various event handlers like onChange, onBlur, and onSubmit to capture user interactions and update the form state accordingly.

For instance, the onChange event handler is frequently utilized to monitor changes in form fields, while the onSubmit event handler is used to manage form submission, as an illustration.

Form Libraries and Tools

When building a React app, handling forms and user input is a common requirement. Fortunately, there are several form libraries and tools available that can simplify the process and enhance the user experience. Let’s explore some popular options:

  1. React Hook Form: React Hook Form is a powerful and efficient toolkit designed for forms in React, utilizing React Hooks. It offers a user-friendly API for validating and handling form data effortlessly. With React Hook Form, you can implement custom validation rules, conditionally validate fields, and effectively manage errors. To illustrate its usage, here’s an example of how you can use React Hook Form.
import { useForm } from 'react-hook-form';
const LoginForm = () => {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('email')} placeholder="Email" />
      <input {...register('password')} type="password" placeholder="Password" />
      <button type="submit">Submit</button>
    </form>
  );
};
  1. Formik: Formik is a well-known form library designed for React, with the goal of making form handling, validation, and submission easier. It adopts a declarative approach to managing forms, enabling you to easily define form fields, validation rules, and submission actions. To illustrate its usage, here’s a practical demonstration of how Formik can be implemented:
import { Formik, Form, Field, ErrorMessage } from 'formik';

const LoginForm = () => {
  const initialValues = {
    email: '',
    password: '',
  };
  const onSubmit = (values) => {
    console.log(values);
  };
  return (
    <Formik initialValues={initialValues} onSubmit={onSubmit}>
      <Form>
        <Field type="email" name="email" placeholder="Email" />
        <ErrorMessage name="email" component="div" />
        <Field type="password" name="password" placeholder="Password" />
        <ErrorMessage name="password" component="div" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};
  1. Yup: Yup is an influential validation library that seamlessly integrates with popular form libraries like Formik and React Hook Form. It enables you to establish validation schemas and effortlessly apply them to your form components. Yup offers a user-friendly and expressive syntax to articulate validation rules, including mandatory fields, string lengths, and email formats. To illustrate, let’s consider an example of utilizing Yup alongside Formik.
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
const validationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Email is required'),
  password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
});
const LoginForm = () => {
  const initialValues = {
    email: '',
    password: '',
  };
  const onSubmit = (values) => {
    console.log(values);
  };
  return (
    <Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}>
      <Form>
        <Field type="email" name="email" placeholder="Email" />
        <ErrorMessage name="email" component="div" />
        <Field type="password" name="password" placeholder="Password" />
        <ErrorMessage name="password" component="div" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};

Conclusion

Building forms in React is a fundamental aspect of creating interactive and user-friendly web applications. The benefits of building forms with React for businesses are simply fantastic! With reusable components and streamlined development processes, React can help businesses create high-quality, responsive web applications quickly and efficiently. Furthermore, with the ability to dynamically update form elements, businesses can create rich, interactive user experiences that keep customers engaged and coming back for more.

If you have any questions regarding the topic, visit our page for the answers.

Course Schedule

Name Date Details
Web Development Courses 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.