This tutorial will show you how to persist user inputs after form submit in Remix.
- Remix installed
- Create a new app with
remix new
and select theapp
template - Open
app/routes/index.tsx
and replace the content with the following:
import { Link, Outlet, useLocation } from "react-router-dom";
import { useQuery } from "remix";
import { Meta, Links, Scripts, LiveReload } from "remix";
import { Form, useActionData, useCatch } from "remix";
import { json } from "remix-utils";
export function meta() {
return {
title: "Remix App",
description: "Welcome to Remix!",
};
}
export function links() {
return [
{ rel: "stylesheet", href: "app.css" },
{ rel: "icon", href: "favicon.ico" },
];
}
export function scripts() {
return [{ src: "app.js" }];
}
- Add a form to the
index.tsx
file:
export default function Index() {
const location = useLocation();
const query = new URLSearchParams(location.search);
const name = query.get("name") || "";
return (
<div>
<h1>Hello {name}!</h1>
<form method="post">
<label htmlFor="name">Name</label>
<input id="name" name="name" type="text" defaultValue={name} />
<button type="submit">Submit</button>
</form>
</div>
);
}
- Add a
post
handler to theindex.tsx
file:
export function action({ request }: { request: Request }) {
const form = new URLSearchParams(await request.text());
const name = form.get("name") || "";
return json({ name }, { status: 303, headers: { location: `/?name=${name}` } });
}
- Run
remix dev
and open http://localhost:3000 in your browser