Updating Data

김동현·2023년 3월 16일
0

React Router

목록 보기
11/31

<Form> 컴포넌트로 데이터를 업데이트 해보자.

Create the edit component

touch src/routes/edit.jsx

Add the edit page UI

import { Form, useLoaderData } from "react-router-dom";

export default function EditContact() {
  const { contact } = useLoaderData();

  return (
    <Form method="post" id="contact-form">
      <p>
        <span>Name</span>
        <input
          placeholder="First"
          aria-label="First name"
          type="text"
          name="first"
          defaultValue={contact.first}
        />
        <input
          placeholder="Last"
          aria-label="Last name"
          type="text"
          name="last"
          defaultValue={contact.last}
        />
      </p>
      <label>
        <span>Twitter</span>
        <input
          type="text"
          name="twitter"
          placeholder="@jack"
          defaultValue={contact.twitter}
        />
      </label>
      <label>
        <span>Avatar URL</span>
        <input
          placeholder="https://example.com/avatar.jpg"
          aria-label="Avatar URL"
          type="text"
          name="avatar"
          defaultValue={contact.avatar}
        />
      </label>
      <label>
        <span>Notes</span>
        <textarea
          name="notes"
          defaultValue={contact.notes}
          rows={6}
        />
      </label>
      <p>
        <button type="submit">Save</button>
        <button type="button">Cancel</button>
      </p>
    </Form>
  );
}

Add the new edit route

/* existing code */
import EditContact from "./routes/edit";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    errorElement: <ErrorPage />,
    loader: rootLoader,
    action: rootAction,
    children: [
      {
        path: "contacts/:contactId",
        element: <Contact />,
        loader: contactLoader,
      },
      {
        path: "contacts/:contactId/edit",
        element: <EditContact />,
        loader: contactLoader,
      },
    ],
  },
]);

root route의 outlet에 랜더링 하고 싶기때문에 Contact route의 sibling route로 만들었다.

contactLoader 이 재사용된 것을 볼 수 있다.

튜토리얼에서는 그냥 저렇게 했지만(게을러서), 일반적으로는 각각 route마다 독자적인 loader가 있기 때문에 저렇게 공유할 필요는 없다.

"edit" 버튼을 누르면 다음과 같은 화면이 나타난다.

출처 : 리액트 라우터 공식 홈페이지➡️

profile
프론트에_가까운_풀스택_개발자

0개의 댓글