New and edit form, action reuse options #1300
-
On initial stages of exploring Remix (Pardon me if its a dumb question :)), I was looking at blog post and jokes example. We have example shown where user is entering details in form and that is getting POSTed and user is redirected back. Was thinking about edit scenario (For which seems like we need to create separate route, is it not possible to use new form route itself for edit scenario to populate fields and for new leave them blank |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I just abstracted the form into its own component that accepted props to prepopulate values or display errors if they exist. As well as a boolean to toggle editing vs creating text. import { useEffect, useState } from "react";
import { Form, useTransition } from "remix";
import { PostInput } from "~/post";
interface PostFormProps {
values?: PostInput;
errors: { [key in keyof PostInput]?: boolean };
editing?: boolean;
}
export const PostForm = ({ errors, values, editing }: PostFormProps) => {
const transition = useTransition();
return (
<Form method="post" key={values?.slug}>
<p>
<label>
Post Title: {errors?.title ? <em>Title is required</em> : null}
<input type="text" name="title" defaultValue={values?.title} />
</label>
</p>
<p>
<label>
Post Slug: {errors?.slug ? <em>Slug is required</em> : null}
<input type="text" name="slug" defaultValue={values?.slug} />
</label>
</p>
<p>
<label htmlFor="markdown">Markdown:</label>{" "}
{errors?.markdown ? <em>Markdown is required</em> : null}
<br />
<textarea
id="markdown"
rows={20}
cols={30}
name="markdown"
defaultValue={values?.markdown}
/>
</p>
<p>
<button type="submit">
{transition.submission
? editing
? "Editing..."
: "Creating..."
: editing
? "Edit Post"
: "Create Post"}
</button>
</p>
</Form>
);
}; |
Beta Was this translation helpful? Give feedback.
I just abstracted the form into its own component that accepted props to prepopulate values or display errors if they exist. As well as a boolean to toggle editing vs creating text.