Menu
Coddy logo textTech

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 icon

Challenge

Beginner

The 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.

  1. In app/page.jsx, import addItem from './actions'.
  2. Wrap the input and the button in a <form> with id="add-form".
  3. 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>
    );
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Next.js Essentials