React Forms


As in HTML, React uses forms to allow users to interact with a webpage.


Adding Forms in React

You can add the React form like anything else:


Example

Add a form that allows users to enter their name:

function MyForm() {
            return (
              <form>
                <label>Enter your name:
                  <input type="text" />
                </label>
              </form>
            )
          }
ReactDOM.render(<MyForm />, document.getElementById('root'));
          

This will work as usual, the form will be submitted and the page will restart.

But this is usually not what we want to happen in React.

We want to prevent this automatic behavior and allow React to control the form.



Handling Forms

Managing forms about how you handle data when it changes value or is sent.

In HTML, form data is usually handled by DOM.

In React, form data is usually handled in sections.

When data is handled by components, all data is stored in component mode.

You can control changes by adding event holders to the onChange attribute.

We may useState Hook to track each input value and provide a "single source of truth" for the entire application.


See the React Hooks section for more information on Hooks.


Example

Use the onChange Hook to manage the input:

import { useState } from "react";
            import ReactDOM from 'react-dom';
            
            function MyForm() {
              const [name, setName] = useState("");
            
              return (
                <form>
                  <label>Enter your name:
                    <input
                      type="text" 
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                    />
                  </label>
                </form>
              )
            }
            
ReactDOM.render(<MyForm />, document.getElementById('root'));
            


Submitting Forms

You can control the submission action by adding the event host to the onSubmits <form> attribute:


Example

Add a submit button and an event handler in the onSubmit attribute:

import { useState } from "react";
            import ReactDOM from 'react-dom';
            
            function MyForm() {
              const [name, setName] = useState("");
            
              const handleSubmit = (event) => {
                event.preventDefault();
                alert('The name you entered was: ${name}')
              }
            
              return (
                <form onSubmit={handleSubmit}>
                  <label>Enter your name:
                    <input 
                      type="text" 
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                    />
                  </label>
                  <input type="submit" />
                </form>
              )
            }
            
ReactDOM.render(<MyForm />, document.getElementById('root'));
            


Multiple Input Fields

You can control more than one input field values ​​by adding a name attribute to each component.

We will start our situation with something empty.

To access the fields in the event manager use event.target.name and the syntax for event.target.value.

To update status, use square brackets [bracket notation] next to the property name.


Example

Write a form with two input fields:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function MyForm() {
              const [inputs, setInputs] = useState({});
            
              const handleChange = (event) => {
                const name = event.target.name;
                const value = event.target.value;
                setInputs(values => ({...values, [name]: value}))
              }
            
              const handleSubmit = (event) => {
                event.preventDefault();
                alert(inputs);
              }
            
              return (
                <form onSubmit={handleSubmit}>
                  <label>Enter your name:
                  <input 
                    type="text" 
                    name="username" 
                    value={inputs.username || ""} 
                    onChange={handleChange}
                  />
                  </label>
                  <label>Enter your age:
                    <input 
                      type="number" 
                      name="age" 
                      value={inputs.age || ""} 
                      onChange={handleChange}
                    />
                    </label>
                    <input type="submit" />
                </form>
              )
            }
            
ReactDOM.render(<MyForm />, document.getElementById('root'));

Note: We use the same event host function in both input fields, we can write one event host individually, but this gives us a much cleaner code and is the preferred method in React.



Textarea

The elementarea element in React is slightly different from standard HTML.

In HTML the value of textarea was text between the first tag <textarea> and the last tag <textarea>.


<textarea>
            Content of the textarea.
          </textarea>

In React the value of the textarea is set to a value attribute. We will use the useState Hook to generate text area value:


Example

A simple textarea with some content:

import { useState } from "react";
            import ReactDOM from "react-dom";
            
            function MyForm() {
              const [textarea, setTextarea] = useState(
                "The content of a textarea goes in the value attribute"
              );
            
              const handleChange = (event) => {
                setTextarea(event.target.value)
              }
            
              return (
                <form>
                  <textarea value={textarea} onChange={handleChange} />
                </form>
              )
            }
            
ReactDOM.render(<MyForm />, document.getElementById('root'));


Select

The drop-down list, or selected box, on React is also slightly different from HTML.

in HTML, the selected drop-down list is defined by the selected attribute:


HTML
<select>
            <option value="Ford">Ford</option>
            <option value="Volvo" selected>Volvo</option>
            <option value="Fiat">Fiat</option>
          </select>

In React, the selected value is defined by a value attribute in the select tags:


Example

A simple select box, where the selected value "Volvo" is initialized in the constructor:

function MyForm() {
            const [myCar, setMyCar] = useState("Volvo");
          
            const handleChange = (event) => {
              setMyCar(event.target.value)
            }
          
            return (
              <form>
                <select value={myCar} onChange={handleChange}>
                  <option value="Ford">Ford</option>
                  <option value="Volvo">Volvo</option>
                  <option value="Fiat">Fiat</option>
                </select>
              </form>
            )
          }
          


By making these minor changes to <textarea> and <select>, React is able to handle all aspects of the installation in the same way