Back to results for “Server Actions & Mutations”
Next.js › Server Actions & Mutations

How do you call a server action directly from a button click inside a client component, rather than through a form submission?

Intermediate

Answer

You import the server action function into your client component and call it directly inside an event handler, such as onClick, just like you would call any other asynchronous function, and Next.js handles sending that call to the server behind the scenes.
'use client';
import { deletePost } from './actions';

export default function DeleteButton({ postId }) {
  return <button onClick={() => deletePost(postId)}>Delete</button>;
}
Real-world example A blog admin panel lets an editor delete a post with a single button click, calling a server action directly rather than needing to submit a form for such a simple action.

Common follow-ups: Does calling a server action from a button require any special setup compared to a form?;How do you show a loading state while a button triggered server action runs?