Forms in React : From Inputs to Controlled Components
You have probably written HTML forms before, and so the structure below resonates with you. Perhaps you even smile because, this one, you understand. <form> <input type= "text" /> <button> Submit </button> </form> If you have done this, you know what happens when you click the button. The whole form reloads, the changes or inputs are cleared. This is the default behavior of forms in HTML. In…
In the world of web development, HTML forms have always been a fundamental building block for user interaction. These forms typically reload the entire page whenever a user submits data, clearing any changes or inputs made. However, React offers a more controlled approach to handling form inputs and behavior.
Traditionally, HTML forms are considered uncontrolled inputs, meaning there's no single source of truth for the value of a field. This can lead to unpredictable behavior when the form is submitted. React introduces the concept of controlled inputs, where the form's data is managed and controlled by the React state.
To create a controlled input in React, you need to add two essential properties to the input element: `value` and `onChange`. The `value` property represents the content of the input field, such as the text entered in a Name field. The `onChange` property is a function that gets triggered every time the input changes. This function is invoked each time a key is pressed within the field, allowing you to update the React state accordingly.
Let's write a simple React input to illustrate this concept:
```javascript
import { useState } from 'react';
function Form() {
const [name, setName] = useState('');
return (
<input
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
);
}
```
In this example, we declare a state variable `name` and a function `setName` to update it. We then set the `value` of the input to `name` and attach an `onChange` event handler that updates `name` with the value entered by the user.
When the user types text into the input field, the `onChange` function is triggered, which in turn calls `setName` with the new value. This way, the React state is always up-to-date with the user's input, ensuring that the form's behavior remains consistent and predictable.
Handling form submission in React is similar to HTML forms, but with an added layer of control. To prevent the default page reload behavior, you can add the `event.preventDefault()` line inside the `handleSubmit` function. By doing this, the form data remains in the React state, allowing you to manipulate it before submission if needed.
For forms with multiple fields, you can create separate state variables for each field, like `const [name, setName] = useState('');` and `const [email, setEmail] = useState('');`. However, this approach can lead to repetitive code. A more concise way to handle multiple fields is to use a single `useState` with an object, like `const [formData, setFormData] = useState({name: '', email: '', password: ''})`. This consolidates all the input states into one variable, making the code cleaner and easier to manage.
React supports various input types, such as checkboxes and select dropdowns, with similar logic and minor tweaks to the properties used. The key is to maintain control over the state and ensure that the form's behavior aligns with your expectations.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.