Topic 27 of 39
Form Submissions
Overview
Next.js enhances the standard HTML <form> element to work natively with Server Actions. By passing a Server Action to the action attribute, forms work even if JavaScript is disabled, providing excellent progressive enhancement.
Syntax
tsx
import { createPost } from './actions';
export default function NewPostForm() {
return (
// 'action' takes the Server Action directly
<form action={createPost} className="flex flex-col gap-4">
<input type="text" name="title" placeholder="Post Title" required />
<textarea name="content" placeholder="Content" />
<button type="submit">Publish</button>
</form>
);
}Common Pitfalls
- Using
onSubmitwithe.preventDefault()out of habit, which disables the progressive enhancement benefits of Server Actions. - Not providing feedback for pending states. You must use the
useFormStatushook in a child component to show loading spinners.
Interview Questions
Q:
How do you show a loading state during a Server Action form submission?
A:
You extract the submit button into a separate Client Component and use the useFormStatus() hook from react-dom to check the pending state.
Real-World Example
A robust form button that disables itself while submitting.
example
tsx
'use client';
import { useFormStatus } from 'react-dom';
export function SubmitButton() {
const { pending } = useFormStatus();
return (
<button disabled={pending}>
{pending ? 'Submitting...' : 'Save Data'}
</button>
);
}Check Your Knowledge
Test your understanding of Form Submissions with these quick questions.