Nextjs Fundamentals · Server Functions & Mutations

Submitting a form to an action

<form action>

Submitting a form to an action

React extends the HTML <form> element so its action prop accepts a Server Function instead of a URL:

// app/ui/form.tsx
import { createPost } from '@/app/actions';

export function Form() {
  return (
    <form action={createPost}>
      <input type="text" name="title" />
      <button type="submit">Create</button>
    </form>
  );
}

When the form is submitted, React calls the Server Function and passes it the form's FormData. Read fields with the native methods:

'use server';

export async function createPost(formData: FormData) {
  const title = formData.get('title');
  // mutate data...
}

In a Server Component this works even before JavaScript has loaded: the browser performs a native form POST to the Server Function, so the form is progressively enhanced by default. In a Client Component, submissions are queued until hydration, after which the browser does not refresh on submit.

You can also pass an action to a Client Component as a prop and attach it to that component's <form action={...}>. The round-trip is still a POST to the Server Function; only where the form is rendered changes.

You are about to answer a short quiz on <form action>.

  1. React's <form> element accepts a Server Function as its action.
  2. A Server Function invoked from a form automatically receives a ___ object.
  3. A form in a Server Component only works after JavaScript has loaded.
  4. The form's round-trip to a Server Function uses the POST method.
  5. You can also attach a Server Action to a button with the ___ prop.