Forms That Act
Part of the Next.js Essentials section of Coddy's React journey — lesson 30 of 47.
In plain HTML, a form's action is a URL to POST to. In Next.js you can hand it a function instead:
import { addItem } from './actions';
<form action={addItem}>
<input name="text" />
<button type="submit">Add</button>
</form>On submit, React does three things for you: it stops the browser's normal page-reloading submit, collects the form's named fields into a FormData object, and calls your action with it.
Notice what is not there: no onSubmit, no event.preventDefault(), no state. And this page is still a Server Component: the action is data being passed along, not an event handler, so it crosses the boundary happily.
One thing to brace for: the item is saved, but the list on screen won't change yet. The page already rendered on the server, and nothing has told it to look again. Two lessons from now you'll fix that in one line.
Challenge
BeginnerThe shopping list has an input and a button, but nothing connects them to the server. The action is already written for you in app/actions.js.
- In
app/page.jsx, importaddItemfrom'./actions'. - Wrap the input and the button in a
<form>withid="add-form". - Give that form
action={addItem}.
Leave the input's name="text" alone: the action reads the field by that name.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing3Layouts & Metadata
The Root LayoutShared NavigationNested LayoutsPage MetadataDynamic MetadataRecap: Layouts6Server Actions
What Is a Server ActionForms That ActReading Form DataRefreshing the PageRecap: Server Actions