Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Working with Forms

Forms are extremely common in apps, so it’s essential to be able to efficiently implement them. In some apps, forms can be large and complex, and getting them to perform well is challenging.

In this chapter, we’ll learn how to build forms in React using different approaches. The example form we will make here is a contact form that you would often see on company websites. It will contain a handful of fields and some validation logic.

The first approach to building a form will be to store field values in the state. We will see how this approach can bloat code and hurt performance. The next approach embraces the browser’s native form capabilities, reducing the amount of code required and improving performance. We will then use React Router’s Form component, which we briefly covered in Chapter 6, Routing with React Router. The final approach will be to use a popular library called React Hook Form. We’ll experience how React Hook...

Technical requirements

We will use the following technologies in this chapter:

All the code snippets in this chapter can be found online at https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition/tree/main/Chapter7.

Using controlled fields

In this section, we will build the first version of our contact form. It will contain fields for the user’s name, email address, contact reason, and any additional notes the user may want to make.

This method will involve the use of controlled fields, which is where field values are stored in the state. We will use this approach to implement the form – however, in doing so, we will pay attention to the amount of code required and the negative impact on performance; this will help you see why other methods are better.

To get started, first, we need to create a React and TypeScript project, as in previous chapters.

Creating the project

We will develop the form using Visual Studio Code and a new Create React App based project setup. We’ve previously covered this several times, so we will not cover the steps in this chapter – instead, refer to Chapter 3, Setting Up React and TypeScript. Create the project for the contact form...

Using uncontrolled fields

Uncontrolled fields are the opposite of controlled fields – it’s where field values aren’t controlled by state. Instead, native browser features are used to obtain field values. In this section, we will refactor the contact form to use uncontrolled fields and see the benefits.

Carry out the following steps:

  1. Open ContactPage.tsx and start by removing useState from the React import, because this is no longer required.
  2. Then, at the top of the component function, remove the call to useState (this iteration of the form won’t use any state).
  3. Remove the value and onChange props from the field editors, because we are no longer controlling field values with the state.
  4. Now, add a name attribute on all the field editors as follows:
    <form onSubmit={handleSubmit}>
      <div className={fieldStyle}>
        <label htmlFor="name">Your name</label>
        ...

Using React Router Form

In Chapter 6, we started to learn about React Router’s Form component. We learned that Form is a wrapper around the HTML form element that handles the form submission. We will now cover Form in more detail and use it to provide a nice submission success message on our contact form.

Carry out the following steps:

  1. First, install React Router by executing the following command in the terminal:
    npm i react-router-dom
  2. Now, let’s create a ThankYouPage component, which will inform the user that their submission has been successful. To do this, create a file called ThankYouPage.tsx in the src folder with the following content:
    import { useParams } from 'react-router-dom';
    export function ThankYouPage() {
      const { name } = useParams<{ name: string }>();
      return (
        <div className="flex flex-col py-10 max-w-md       mx-auto">
          <div
     ...

Using native validation

In this section, we will add the required validation to the name, email, and reason fields and ensure that the email matches a particular pattern. We will use standard HTML form validation to implement these rules.

Carry out the following steps:

  1. In ContactPage.tsx, add a required attribute to the name, email, and reason field editors to add HTML form required validation for these fields:
    <Form method="post">
      <div className={fieldStyle}>
        ...
        <input type="text" id="name" name="name" required />
      </div>
      <div className={fieldStyle}>
        ...
        <input type="email" id="email" name="email" required />
      </div>
      <div className={fieldStyle}>
        ...
        <select id="...

Using React Hook Form

In this section, we will learn about React Hook Form and use it to improve the validation user experience in our contact form.

Understanding React Hook Form

As the name suggests, React Hook Form is a React library for building forms. It is very flexible and can be used for simple forms such as our contact form, as well as large forms with complex validation and submission logic. It is also very performant and optimised not to cause unnecessary re-renders. It is also very popular with tens of thousands of GitHub stars and maturing nicely having been first released in 2019.

The key part of React Hooks Form is a useForm hook, which returns useful functions and the state. The following code snippet shows the useForm hook being called:

const {
  register,
  handleSubmit,
  formState: { errors, isSubmitting, isSubmitSuccessful }
} = useForm<FormData>();

useForm has a generic type parameter for the type of the field...

Summary

At the start of this chapter, we learned that field values in a form can be controlled by the state. However, this leads to lots of unnecessary re-rendering of the form. We then realised that not controlling field values with the state and using the FormData interface to retrieve field values instead is more performant and requires less code.

We used React Router’s Form component, which is a wrapper around the native form element. It submits data to a client-side route instead of a server. However, it doesn’t cover validation – we tried using native HTML validation for that, which was simple to implement, but providing a great user experience with native HTML validation is tricky.

We introduced ourselves to a popular forms library called React Hook Form to provide a better validation user experience. It contains a useForm hook that returns useful functions and a state. The library doesn’t cause unnecessary renders, so it is very performant...

Questions

Answer the following questions to check what you have learned about forms in React:

  1. How many times will the following form render after the initial render when Bob is entered into the name field?
    function ControlledForm () {
      const [name, setName] = useState('');
      return (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            console.log(name);
          }}
        >
          <input
            placeholder="Enter your name"
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </form>
      );
    }
  2. How many...

Answers

  1. The form will render three times when Bob is entered into the name field. This is because each change of value causes a re-render because the value is bound to the state.
  2. The form will never re-render when Bob is entered into the name field because its value isn’t bound to the state.
  3. The FormData interface requires the name attribute to be on the input element or it won’t be able to find it and it will return null:
    <input type="search" placeholder="Search ..." name="search" />
  4. For React Hook Form to track the field, the register function needs to be spread on the input element as follows:
    function SearchReactHookForm() {
      const { handleSubmit, register } = useForm();
      return (
        <form
          onSubmit={handleSubmit((search) => console.        log(search))}
        >
          <input
      ...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon