Similar to HTML, React uses forms to enable user interaction with the web page.
Adding Forms in React
You add a form in React just like any other element.
Example:
Create a form that lets users input their name.
function MyForm() {
return (
<form> <label>Enter your name: <input type="text" /> </label> </form>
) } const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<MyForm />);
|
By default, the form will submit and refresh the page, but this is usually not desired in React. Instead, we want to prevent this default behavior and allow React to manage the form.
Handling Forms
Handling forms involves managing data when it changes or is submitted. In HTML, this is typically handled by the DOM, while in React, it is managed by components. React components use the useState
Hook to store and track input values, ensuring a single source of truth for the application’s state, and control changes via onChange
event handlers.
Example:
Utilize the useState Hook to manage the input value.
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
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>
) }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<MyForm />);
|
Submitting Forms
You can manage the submit action by adding an event handler to the onSubmit attribute of the <form>.
Example:
Include a submit button and attach an event handler to the onSubmit attribute.
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
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>
) }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<MyForm />);
|
Multiple Input Fields
You can manage multiple input fields by assigning a name attribute to each element. Initialize the state with an empty object, and use event.target.name and event.target.value to access field values in the event handler. To update the state, use [bracket notation] with square brackets around the property name.
Example:
Create a form with two input fields.
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
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>
) }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<MyForm />);
|
Note: Using the same event handler function for both input fields is preferred in React, as it results in cleaner code compared to writing separate handlers for each field. |