Introduction to Forms in React

react forms intro
10 November 2024

In React, one of the most important and common tasks is to work with forms and manage user input data. Forms give us the ability to receive information from users and we usually need to use this information for specific storage or processing. In this article, we will examine how to work with forms in React and explain practical methods for managing them.

Forms in React, due to a specific property that exists, can behave differently than traditional HTML. In React forms, instead of directly using the DOM for reading and writing data, we typically use state. This allows us to easily track changes and create more complex interactions.

To start working with forms in React, the first step is to use state in the form component. We usually use useState to create and manage this state. This allows us to control the current state of the form and previous states. For example, we can use state to store user input data and then use it for actions upon submission.

It is also important to manage and validate user input data (validation). In the examples and explanations below, we will try to cover these aspects and show how we can improve the consistency and quality of forms.

A Simple Example of a Form in React

In this example, we will build a simple form with input and submit button:


import React, { useState } from 'react';

function SimpleForm() {
    const [inputValue, setInputValue] = useState('');
    
    const handleSubmit = (event) => {
        event.preventDefault();
        console.log('Submitted Value:', inputValue);
    };

    const handleInputChange = (event) => {
        setInputValue(event.target.value);
    };

    return (
        <form onSubmit={handleSubmit}>
            <label>
                Name:
                <input type="text" value={inputValue} onChange={handleInputChange} />
            </label>
            <button type="submit">Submit</button>
        </form>
    );
}

export default SimpleForm;

Step-by-Step Code Explanation

import React, { useState } from 'react';
This line of code imports React and other hooks (like useState) necessary for the component's functionality.

const [inputValue, setInputValue] = useState('');
Here, useState creates a new state variable with an initial value of an empty string, which will be used to store the user input.

const handleSubmit = (event) => { ... }
This function is used to manage the submit event of the form, preventing the default behavior (refreshing the page) and logging the input value to the console.

const handleInputChange = (event) => { ... }
This function handles updating the state with the current value entered by the user.

<form onSubmit={handleSubmit}>...
This line is used for the HTML form structure. The handleSubmit function executes when the form is submitted.

<input type="text" ... />
This input field captures user input based on changes from the user, updating the state with the new value.

<button type="submit">Submit</button>
This button is used to submit the form data and triggers the handleSubmit function.

FAQ

?

How can I control user input in a React form?

?

How can I prevent the default form submission behavior?

?

How can I add simple validation to forms in React?