Similar to HTML, forms in React allow users to interact with web pages. Adding a form in React follows the same approach as adding any other element.
Create a form that lets users input their name:
function UserForm() { return ( <form> <label>Enter your name: <input type="text" /> </label> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);
This will function as expected, submitting the form and refreshing the page. However, this behavior is not ideal in React. Instead, we want to control the form using React to prevent this default behavior.
Handling Forms
Handling forms involves managing the data when it changes or gets submitted. In traditional HTML, form data is managed by the DOM, but in React, form data is typically managed by components.
When the component handles the data, it is stored in the component state. You can manage changes by adding event handlers in the onChange
attribute. The useState
Hook helps track the value of inputs, providing a “single source of truth” for the entire application.
Use the useState
Hook to manage input:
import { useState } from 'react'; import ReactDOM from 'react-dom/client'; function UserForm() { const [userName, setUserName] = useState(""); return ( <form> <label>Enter your name: <input type="text" value={userName} onChange={(e) => setUserName(e.target.value)} /> </label> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);
Submitting Forms
You can manage the submit action by adding an event handler in the onSubmit
attribute of the <form>
element:
Add a submit button and an event handler for submission:
import { useState } from 'react'; import ReactDOM from 'react-dom/client'; function UserForm() { const [userName, setUserName] = useState(""); const handleSubmit = (event) => { event.preventDefault(); alert(`The name you entered was: ${userName}`); } return ( <form onSubmit={handleSubmit}> <label>Enter your name: <input type="text" value={userName} onChange={(e) => setUserName(e.target.value)} /> </label> <input type="submit" /> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);
Multiple Input Fields
To manage multiple input fields, you can add a name
attribute to each element. Initialize your state with an empty object, and use event.target.name
and event.target.value
to access the fields in the event handler. Use square bracket notation to update the state.
Create a form with two input fields:
import { useState } from 'react'; import ReactDOM from 'react-dom/client'; function UserForm() { const [formData, setFormData] = useState({}); const handleChange = (event) => { const { name, value } = event.target; setFormData((prevData) => ({ ...prevData, [name]: value })); } const handleSubmit = (event) => { event.preventDefault(); alert(JSON.stringify(formData)); } return ( <form onSubmit={handleSubmit}> <label>Enter your name: <input type="text" name="userName" value={formData.userName || ""} onChange={handleChange} /> </label> <label>Enter your age: <input type="number" name="userAge" value={formData.userAge || ""} onChange={handleChange} /> </label> <input type="submit" /> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);
Note: Using a single event handler for multiple input fields results in cleaner code and is the recommended approach in React.
Textarea
The textarea
element in React differs slightly from regular HTML. In HTML, the value of a textarea
is placed between the opening and closing tags. In React, it is set using the value
attribute, and we can manage it using the useState
Hook.
A simple textarea
with some initial content:
import { useState } from 'react'; import ReactDOM from 'react-dom/client'; function UserForm() { const [textareaContent, setTextareaContent] = useState( "The content of a textarea goes in the value attribute" ); const handleChange = (event) => { setTextareaContent(event.target.value); } return ( <form> <textarea value={textareaContent} onChange={handleChange} /> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);
Select
A dropdown list, or select
box, in React is also somewhat different from HTML. In HTML, the selected value in the dropdown was defined using the selected
attribute. In React, the selected value is set using the value
attribute on the select
tag.
A simple select
box where the selected value “Volvo” is initialized:
import { useState } from 'react'; import ReactDOM from 'react-dom/client'; function UserForm() { const [selectedCar, setSelectedCar] = useState("Volvo"); const handleChange = (event) => { setSelectedCar(event.target.value); } return ( <form> <select value={selectedCar} onChange={handleChange}> <option value="Ford">Ford</option> <option value="Volvo">Volvo</option> <option value="Fiat">Fiat</option> </select> </form> ); } const rootElement = ReactDOM.createRoot(document.getElementById('root')); rootElement.render(<UserForm />);