Adding a Note from a Form
Adding a note is a form that sends a new title to the API. The form uses a controlled input and a submit handler.
The input value in state
const [title, setTitle] = useState('');A controlled input
<input value={title} onChange={(e) => setTitle(e.target.value)} />Stopping the reload on submit
function handleAdd(event) {
event.preventDefault();
}Example
import { useState } from 'react';
export default function App() {
const [notes] = useState([
{ id: 1, title: 'Buy milk' },
{ id: 2, title: 'Ship MERN' },
{ id: 3, title: 'Read a book' },
]);
const [title] = useState('');
return (
<div>
<h1>Notes</h1>
<form>
<input value={title} onChange={() => {}} />
<button>Add note</button>
</form>
<ul>
{notes.map((note) => (
<li key={note.id}>{note.title}</li>
))}
</ul>
</div>
);
}Key points
- A controlled input keeps its value in state.
- Typing in the input updates that state.
- Submitting the form sends a POST request with the title.
- The submit handler stops the browser from reloading the page.
In this example, the input starts empty, so the first render shows an empty box above the three seed notes. The input is controlled, so its value always matches state. In the real app, typing updates the title, and submitting the form sends a POST request with that title.
Note
The form clears the input after a successful submit.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What keeps the input value in step with state?