Use Remix Action to handle form submission

In this tutorial, we'll learn how to use the Action to handle form submission in Remix.

Action is a sever-side function to handle data mutation. It's the way to handle form submission in Remix.

If you make a POST request to your route, the Action is execeuted. If you make a GET request, the Action is not executed.

Let's add a new route to our app called /signup and create a form to handle user signup.

Add the following code to app/routes/signup.tsx:

import type { ActionArgs } from "@remix-run/node";
import { Form } from "@remix-run/react";
import { redirect } from "@remix-run/node";

// Action to handle form submission
export async function action({ request }: ActionArgs) {
  // Get the form data from the request
  const body = await request.formData();

  // Use the `get` method to get the value of the form field
  const newUser = {
    name: body.get("name"),
    email: body.get("email"),
    password: body.get("password"),
  };

  // You can use newUser to create a new user in your database
  console.log(newUser);

  // Redirect to the user page
  return redirect("/user");
}

// Route to render the form
export default function User() {
  return (
    <>
      <Form method="post">
        <input type="text" name="name" placeholder="Name" />
        <input type="email" name="email" placeholder="Email" />
        <input type="password" name="password" placeholder="Password" />
        <button type="submit">Create User</button>
      </Form>
    </>
  );
}

Note the use of the Form component. It's a wrapper around the HTML form element and use the fetch API to submit the form data to the server.

You can inspect the request from the browser's network tab to see the form data.

More Articles

  1. Use Remix Action to handle form submission
  2. Use Remix Loader to fetch data from an external API
  3. Validating form data in Remix using Zod and Action function
  4. Add a search form in Remix with data fetching
  5. Show a flash message in Remix after form submission
  6. Discover the best SaaS Starter Kits based on Remix