How to build forms in React

Forms are an important part of React web applications because they enable users to enter and submit data directly in components ranging from a login screen to a sign-out page. 

React form libraries allow us to access a wide range of features without having to build everything from scratch. Many developers use React form libraries for complex form handling, such as data validation, styling, and dynamic rendering, allowing them to concentrate on business logic.

Building forms in React

To fully understand this, it is recommended that you have the following:

  • Basic knowledge of JavaScript

  • Basic knowledge of React

  • Node.js as the runtime environment

Form elements like <input>, <textarea>, and <select> in HTML typically keep their own state and update it based on user input. However, in React, the state of these input elements is typically stored in the state property of components and only updated with setState().

Form input types

In most cases, controlled components are recommended for implementing forms since in this, a React component handles the form data. The alternative is to use uncontrolled components, in which the DOM handles form data.

Controlled components

The controlled component's form input element values are entirely driven by event handlers, and the value of the input element is always deduced from the state. We create a controlled component by connecting the form element (<input>, <textarea> or <select>) to the state by setting its attribute value and the event onChange.

Let's see an example of a controlled component:

const { useState } from 'react';
function Controlled () {
const [email, setEmail] = useState();
const handleInput = (e) => setEmail(e.target.value);
return <input type="text" value={email} onChange={handleInput} />;
}

Uncontrolled components

When writing an uncontrolled component, we can use a ref to get form values from the DOM rather than writing an event handler for each state update. Furthermore, we can access the input's DOM node and extract its value by a ref as well.

const { useRef } from 'react';
function Example () {
const inputRef = useRef(null);
return <input type="text" defaultValue="bar" ref={inputRef} />
}

Example

To begin, we'll create a simple form with no styling – a bunch of textarea inputs. For this example, we'll create a form with the following inputs:

  • First name

  • Last name

  • Age

  • City

  • A submit button

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Explanation

  • Lines 3–12: We create variables to store the states; firstName, lastName, age and city and initialize them to empty strings in the constructor.

  • Lines 14–28: We create functions handleFirstName, handlelastName, handleage and handlecity that manage updating the React states of respective variables.

  • Lines 30–33: The function handleSubmit, which is called when the form is submitted, prevents default form values from being submitted by using event.preventDefault().

  • Line 37: A form is created that calls the handleSubmit function on a submit form request.

  • Lines 38–63: Input fields are created that take user input for first name, last name, age and city and then call the respective handle function to update the state.

  • Lines 65: An HTML button is defined that calls the function handleSubmit when it is clicked.

Copyright ©2024 Educative, Inc. All rights reserved