Skip to content

Latest commit

Β 

History

History
414 lines (317 loc) Β· 16.8 KB

File metadata and controls

414 lines (317 loc) Β· 16.8 KB
title <form>

λ‚΄μž₯ λΈŒλΌμš°μ € <form> μ»΄ν¬λ„ŒνŠΈλ‘œ 정보 μ œμΆœμ„ μœ„ν•œ λŒ€ν™”ν˜• μ»¨νŠΈλ‘€μ„ λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€.

<form action={search}>
    <input name="query" />
    <button type="submit">검색</button>
</form>

레퍼런슀 {/reference/}

<form> {/form/}

정보 μ œμΆœμ„ μœ„ν•œ λŒ€ν™”ν˜• μ»¨νŠΈλ‘€μ„ μƒμ„±ν•˜κΈ° μœ„ν•΄, λ‚΄μž₯ λΈŒλΌμš°μ € <form> μ»΄ν¬λ„ŒνŠΈλ₯Ό λ Œλ”λ§ν•˜μ„Έμš”.

<form action={search}>
    <input name="query" />
    <button type="submit">검색</button>
</form>

μ•„λž˜ μ˜ˆμ‹œλ₯Ό μ°Έκ³ ν•˜μ„Έμš”.

Props {/props/}

<form>은 λͺ¨λ“  곡톡 μ—˜λ¦¬λ¨ΌνŠΈ Propsλ₯Ό μ§€μ›ν•©λ‹ˆλ‹€.

action: a URL or function. When a URL is passed to action the form will behave like the HTML form component. When a function is passed to action the function will handle the form submission in a Transition following the Action prop pattern. The function passed to action may be async and will be called with a single argument containing the form data of the submitted form. The action prop can be overridden by a formAction attribute on a <button>, <input type="submit">, or <input type="image"> component.

주의 사항 {/caveats/}

  • ν•¨μˆ˜λ₯Ό actionμ΄λ‚˜ formAction에 μ „λ‹¬ν•˜λ©΄, HTTP λ©”μ„œλ“œλŠ” method ν”„λ‘œνΌν‹°μ˜ κ°’κ³Ό 관계없이 POST둜 μ²˜λ¦¬ν•©λ‹ˆλ‹€.

μ‚¬μš©λ²• {/usage/}

<<<<<<< HEAD

ν΄λΌμ΄μ–ΈνŠΈμ—μ„œ 폼 제좜 μ²˜λ¦¬ν•˜κΈ° {/handle-form-submission-on-the-client/}

폼이 제좜될 λ•Œ ν•¨μˆ˜λ₯Ό μ‹€ν–‰ν•˜κΈ° μœ„ν•΄, 폼의 action ν”„λ‘œνΌν‹°μ— ν•¨μˆ˜λ₯Ό μ „λ‹¬ν•˜μ„Έμš”. formDataκ°€ ν•¨μˆ˜μ— 인수둜 μ „λ‹¬λ˜μ–΄, νΌμ—μ„œ μ „λ‹¬λœ 데이터에 μ ‘κ·Όν•  수 μžˆμŠ΅λ‹ˆλ‹€. 이 점이 URL만 λ°›λ˜ κΈ°μ‘΄ HTML action과의 μ°¨μ΄μ μž…λ‹ˆλ‹€. After the action function succeeds, all uncontrolled field elements in the form are reset.

Handle form submission with an event handler {/handle-form-submission-with-an-event-handler/}

Pass a function to the onSubmit event handler to run code when the form is submitted. By default, the browser sends the form data to the current URL and refreshes the page, so call e.preventDefault() to override that behavior.

This example reads the submitted values with new FormData(e.target), which collects every field by its name. This keeps the inputs uncontrolled. If you instead control an input with state, read from that state on submit rather than from FormData.

export default function Search() {
  function handleSubmit(e) {
    // Prevent the browser from reloading the page
    e.preventDefault();

    // Read the form data
    const form = e.target;
    const formData = new FormData(form);
    const query = formData.get("query");
    alert(`You searched for '${query}'`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="query" />
      <button type="submit">Search</button>
    </form>
  );
}

Reading form data with onSubmit works in every version of React and gives you direct access to the submit event, so you can call e.preventDefault() and read the data yourself. Passing the function to the action prop instead runs the submission in a Transition. React then tracks the pending state, sends thrown errors to the nearest error boundary, and lets the form work with useActionState and useOptimistic. An action can also be a Server Function, which onSubmit does not support.

Handle form submission with an action prop {/handle-form-submission-with-an-action-prop/}

Pass a function to the action prop of form to run the function when the form is submitted. formData will be passed to the function as an argument so you can access the data submitted by the form. This differs from the conventional HTML action, which only accepts URLs. Unlike onSubmit, an action runs in a Transition and calling e.preventDefault() isn't needed. After the action function succeeds, all uncontrolled field elements in the form are reset.

152a471aa9ac2f6f0f3e64c04f39da790d40cf61

export default function Search() {
  function search(formData) {
    const query = formData.get("query");
    alert(`'${query}'을(λ₯Ό) κ²€μƒ‰ν–ˆμŠ΅λ‹ˆλ‹€.`);
  }
  return (
    <form action={search}>
      <input name="query" />
      <button type="submit">검색</button>
    </form>
  );
}

μ„œλ²„ ν•¨μˆ˜μ—μ„œ 폼 제좜 μ²˜λ¦¬ν•˜κΈ° {/handle-form-submission-with-a-server-function/}

μž…λ ₯ 및 제좜 λ²„νŠΌκ³Ό ν•¨κ»˜ <form>을 λ Œλ”λ§ν•˜μ„Έμš”. 폼을 μ œμΆœν•  λ•Œ ν•΄λ‹Ή ν•¨μˆ˜λ₯Ό μ‹€ν–‰ν•˜κΈ° μœ„ν•΄ μ„œλ²„ ν•¨μˆ˜('use server'κ°€ ν‘œμ‹œλœ ν•¨μˆ˜)λ₯Ό 폼의 action ν”„λ‘œνΌν‹°λ‘œ μ „λ‹¬ν•˜μ„Έμš”.

<form action>에 μ„œλ²„ ν•¨μˆ˜λ₯Ό μ „λ‹¬ν•˜λ©΄ μžλ°”μŠ€ν¬λ¦½νŠΈκ°€ ν™œμ„±ν™”λ˜κΈ° μ „μ΄λ‚˜ μ½”λ“œκ°€ λ‘œλ“œλ˜κΈ° 전에 μ‚¬μš©μžκ°€ 폼을 μ œμΆœν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ΄λŠ” μ—°κ²° μƒνƒœλ‚˜ 기계가 λŠλ¦¬κ±°λ‚˜ μžλ°”μŠ€ν¬λ¦½νŠΈκ°€ λΉ„ν™œμ„±ν™”λœ μ‚¬μš©μžμ—κ²Œ μœ μš©ν•˜κ³ , action ν”„λ‘œνΌν‹°μ— URL이 전달될 λ•Œμ™€ 폼이 λ™μž‘ν•˜λŠ” 방식은 λΉ„μŠ·ν•©λ‹ˆλ‹€.

<form>의 μ•‘μ…˜μ— 데이터λ₯Ό μ œκ³΅ν•˜κΈ° μœ„ν•΄ 폼 ν•„λ“œμ˜ hidden을 μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ„œλ²„ ν•¨μˆ˜λŠ” formData λŒ€μ‹  hidden이 적용된 폼 ν•„λ“œ 데이터λ₯Ό 뢈러올 수 μžˆμŠ΅λ‹ˆλ‹€.

import { updateCart } from './lib.js';

function AddToCart({productId}) {
  async function addToCart(formData) {
    'use server'
    const productId = formData.get('productId')
    await updateCart(productId)
  }
  return (
    <form action={addToCart}>
        <input type="hidden" name="productId" value={productId} />
        <button type="submit">μž₯λ°”κ΅¬λ‹ˆμ— μΆ”κ°€</button>
    </form>
  );
}

폼 μ•‘μ…˜μ— λ”°λ₯Έ 데이터λ₯Ό μ œκ³΅ν•˜κΈ° μœ„ν•΄ hidden 폼 ν•„λ“œλ₯Ό μ‚¬μš©ν•˜λŠ” λŒ€μ‹ μ— bindλ₯Ό ν˜ΈμΆœν•΄ μΆ”κ°€ 인수λ₯Ό μ œκ³΅ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ΄λ ‡κ²Œ ν•˜λ©΄ ν•¨μˆ˜μ— 인수둜 μ „λ‹¬λ˜λŠ” formData 외에 μƒˆ 인수(productId)κ°€ ν•¨μˆ˜μ— λ°”μΈλ”©λ©λ‹ˆλ‹€.

import { updateCart } from './lib.js';

function AddToCart({productId}) {
  async function addToCart(productId, formData) {
    "use server";
    await updateCart(productId)
  }
  const addProductToCart = addToCart.bind(null, productId);
  return (
    <form action={addProductToCart}>
      <button type="submit">μž₯λ°”κ΅¬λ‹ˆμ— μΆ”κ°€</button>
    </form>
  );
}

<form>이 μ„œλ²„ μ»΄ν¬λ„ŒνŠΈμ— μ˜ν•΄ λ Œλ”λ§λ˜κ³  μ„œλ²„ ν•¨μˆ˜κ°€ <form>의 action ν”„λ‘œνΌν‹°μ— μ „λ‹¬λ˜λ©΄, 폼은 μ μ§„μ μœΌλ‘œ ν–₯μƒλ©λ‹ˆλ‹€.

폼이 μ œμΆœλ˜λŠ” λ™μ•ˆ λŒ€κΈ° μƒνƒœ 보여주기 {/display-a-pending-state-during-form-submission/}

폼이 μ œμΆœλ˜λŠ” λ™μ•ˆ λŒ€κΈ°Pending μƒνƒœλ₯Ό 보여주기 μœ„ν•΄, <form>이 λ Œλ”λ§λ˜λŠ” μ»΄ν¬λ„ŒνŠΈ μ•ˆμ—μ„œ useFormStatus Hook을 ν˜ΈμΆœν•΄ λ°˜ν™˜λœ pending ν”„λ‘œνΌν‹°λ₯Ό 읽을 수 μžˆμŠ΅λ‹ˆλ‹€.

μ—¬κΈ° 폼이 제좜되고 μžˆμŒμ„ λ‚˜νƒ€λ‚΄κΈ° μœ„ν•΄ pending ν”„λ‘œνΌν‹°λ₯Ό μ‚¬μš©ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

import { useFormStatus } from "react-dom";
import { submitForm } from "./actions.js";

function Submit() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? "μ œμΆœμ€‘..." : "제좜"}
    </button>
  );
}

function Form({ action }) {
  return (
    <form action={action}>
      <Submit />
    </form>
  );
}

export default function App() {
  return <Form action={submitForm} />;
}
export async function submitForm(query) {
    await new Promise((res) => setTimeout(res, 1000));
}

useFormStatus Hook에 λŒ€ν•΄ 더 μ•Œκ³  μ‹Άλ‹€λ©΄, μ°Έκ³  λ¬Έμ„œλ₯Ό ν™•μΈν•˜μ„Έμš”.

λ‚™κ΄€μ μœΌλ‘œ 폼 데이터 μ—…λ°μ΄νŠΈν•˜κΈ° {/optimistically-updating-form-data/}

useOptimistic Hook은 λ„€νŠΈμ›Œν¬ μš”μ²­κ³Ό 같은 λ°±κ·ΈλΌμš΄λ“œμ˜ μž‘μ—…μ΄ λλ‚˜κΈ° 전에 μ‚¬μš©μž μΈν„°νŽ˜μ΄μŠ€μ— λ‚™κ΄€μ μœΌλ‘œ μ—…λ°μ΄νŠΈν•˜λŠ” 방법을 μ œκ³΅ν•©λ‹ˆλ‹€. 폼의 λ§₯λ½μ—μ„œ 이 κΈ°μˆ μ€ 앱을 λ”μš± λ°˜μ‘ν˜•μœΌλ‘œ 느끼게 ν•΄μ€λ‹ˆλ‹€. μ‚¬μš©μžκ°€ 폼을 μ œμΆœν•˜λ©΄ μΈν„°νŽ˜μ΄μŠ€λŠ” μ‚¬μš©μžκ°€ κΈ°λŒ€ν•˜λŠ” 결과물둜 μ¦‰μ‹œ μ—…λ°μ΄νŠΈλ©λ‹ˆλ‹€.

예λ₯Ό λ“€μ–΄, μ‚¬μš©μžκ°€ 폼에 λ©”μ‹œμ§€λ₯Ό μž…λ ₯ν•˜κ³  "전솑" λ²„νŠΌμ„ ν΄λ¦­ν•˜λ©΄ useOptimistic Hook은 "전솑쀑..." 라벨과 ν•¨κ»˜ λ©”μ‹œμ§€κ°€ μ„œλ²„μ— 보내지기 전에 λ¦¬μŠ€νŠΈμ— μ¦‰μ‹œ λ³΄μž…λ‹ˆλ‹€. μ΄λŸ¬ν•œ '낙관적인' μ ‘κ·Ό 방식은 속도와 λ°˜μ‘μ„±μ΄ λ›°μ–΄λ‚˜λ‹€λŠ” 인상을 μ€λ‹ˆλ‹€. κ·Έλ‹€μŒ 폼은 μ‹€μ œλ‘œ λ°±κ·ΈλΌμš΄λ“œμ— λ©”μ‹œμ§€ 보내기λ₯Ό μ‹œλ„ν•©λ‹ˆλ‹€. μ„œλ²„μ— λ©”μ‹œμ§€κ°€ 잘 λ„μ°©ν•˜λ©΄, "전솑쀑..." 라벨은 μ‚¬λΌμ§‘λ‹ˆλ‹€.

import { useOptimistic, useState, useRef } from "react";
import { deliverMessage } from "./actions.js";

function Thread({ messages, sendMessage }) {
  const formRef = useRef();
  async function formAction(formData) {
    addOptimisticMessage(formData.get("message"));
    formRef.current.reset();
    await sendMessage(formData);
  }
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (state, newMessage) => [
      ...state,
      {
        text: newMessage,
        sending: true
      }
    ]
  );

  return (
    <>
      {optimisticMessages.map((message, index) => (
        <div key={index}>
          {message.text}
          {!!message.sending && <small> (전솑쀑...)</small>}
        </div>
      ))}
      <form action={formAction} ref={formRef}>
        <input type="text" name="message" placeholder="Hello!" />
        <button type="submit">전솑</button>
      </form>
    </>
  );
}

export default function App() {
  const [messages, setMessages] = useState([
    { text: "Hello there!", sending: false, key: 1 }
  ]);
  async function sendMessage(formData) {
    const sentMessage = await deliverMessage(formData.get("message"));
    setMessages((messages) => [...messages, { text: sentMessage }]);
  }
  return <Thread messages={messages} sendMessage={sendMessage} />;
}
export async function deliverMessage(message) {
  await new Promise((res) => setTimeout(res, 1000));
  return message;
}

폼 제좜 였λ₯˜ μ²˜λ¦¬ν•˜κΈ° {/handling-form-submission-errors/}

<form>의 action ν”„λ‘œνΌν‹°λ‘œ μ „λ‹¬λœ μ–΄λ–€ ν•¨μˆ˜λŠ” 였λ₯˜λ₯Ό λ˜μ§€κΈ°λ„ ν•©λ‹ˆλ‹€. 이런 였λ₯˜λ₯Ό <form>에 μ—λŸ¬ λ°”μš΄λ”λ¦¬λ₯Ό 감싸 ν•΄κ²°ν•  수 μžˆμŠ΅λ‹ˆλ‹€. λ§Œμ•½ <form>의 action ν”„λ‘œνΌν‹°μ—μ„œ 호좜된 ν•¨μˆ˜κ°€ 였λ₯˜λ₯Ό λ˜μ§„λ‹€λ©΄ μ—λŸ¬ λ°”μš΄λ”λ¦¬μ˜ Fallback이 보이게 λ©λ‹ˆλ‹€.

import { ErrorBoundary } from "react-error-boundary";

export default function Search() {
  function search() {
    throw new Error("search error");
  }
  return (
    <ErrorBoundary
      fallback={<p>폼 제좜 쀑에 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.</p>}
    >
      <form action={search}>
        <input name="query" />
        <button type="submit">검색</button>
      </form>
    </ErrorBoundary>
  );
}
{
  "dependencies": {
    "react": "19.0.0-rc-3edc000d-20240926",
    "react-dom": "19.0.0-rc-3edc000d-20240926",
    "react-scripts": "^5.0.0",
    "react-error-boundary": "4.0.3"
  },
  "main": "/index.js",
  "devDependencies": {}
}

μžλ°”μŠ€ν¬λ¦½νŠΈ 없이 폼 제좜 였λ₯˜ 보여주기 {/display-a-form-submission-error-without-javascript/}

점진적 ν–₯상을 μœ„ν•΄ μžλ°”μŠ€ν¬λ¦½νŠΈ λ²ˆλ“€μ΄ λ‘œλ“œλ˜κΈ° μ „ 였λ₯˜ λ©”μ‹œμ§€λ₯Ό 보여주기 μœ„ν•΄ λ‹€μŒ μš”μ†Œλ“€μ΄ μ§€μΌœμ Έμ•Ό ν•©λ‹ˆλ‹€.

  1. <form> be rendered by a Client Component
  2. the function passed to the <form>'s action prop be a Server Function
  3. the useActionState Hook be used to display the error message

useActionStateλŠ” μ„œλ²„ ν•¨μˆ˜μ™€ 초기 StateλΌλŠ” 두 개의 λ§€κ°œλ³€μˆ˜λ₯Ό κ°€μ§‘λ‹ˆλ‹€. useActionStateλŠ” State λ³€μˆ˜μ™€ μ•‘μ…˜μ΄λΌλŠ” 두 개의 값을 λ°˜ν™˜ν•©λ‹ˆλ‹€. useActionStateλ₯Ό 톡해 λ°˜ν™˜λœ μ•‘μ…˜μ€ 폼의 action ν”„λ‘œνΌν‹°μ— 전달될 수 μžˆμŠ΅λ‹ˆλ‹€. useActionStateλ₯Ό 톡해 λ°˜ν™˜λœ μƒνƒœ λ³€μˆ˜λŠ” 였λ₯˜ λ©”μ‹œμ§€λ₯Ό λ³΄μ—¬μ£ΌλŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€. useActionState에 μ „λ‹¬λœ μ„œλ²„ ν•¨μˆ˜μ—μ„œ λ°˜ν™˜λœ 값은 State λ³€μˆ˜λ₯Ό μ—…λ°μ΄νŠΈν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.

import { useActionState } from "react";
import { signUpNewUser } from "./api";

export default function Page() {
  async function signup(prevState, formData) {
    "use server";
    const email = formData.get("email");
    try {
      await signUpNewUser(email);
      alert(`"${email}"을 λ“±λ‘ν–ˆμ–΄μš”`);
    } catch (err) {
      return err.toString();
    }
  }
  const [message, signupAction] = useActionState(signup, null);
  return (
    <>
      <h1>λ‰΄μŠ€λ ˆν„°μ— κ°€μž…ν•˜μ„Έμš”</h1>
      <p>같은 μ΄λ©”μΌλ‘œ 두 번 κ°€μž…ν•˜μ—¬ 였λ₯˜λ₯Ό ν™•μΈν•˜μ„Έμš”.</p>
      <form action={signupAction} id="signup-form">
        <label htmlFor="email">이메일: </label>
        <input name="email" id="email" placeholder="react@example.com" />
        <button>κ°€μž…ν•˜κΈ°</button>
        {!!message && <p>{message}</p>}
      </form>
    </>
  );
}
let emails = [];

export async function signUpNewUser(newEmail) {
  if (emails.includes(newEmail)) {
    throw new Error("이 이메일 μ£Όμ†ŒλŠ” 이미 λ“±λ‘λ˜μ—ˆμŠ΅λ‹ˆλ‹€.");
  }
  emails.push(newEmail);
}

useActionState λ¬Έμ„œλ₯Ό 톡해 폼 μž‘μ—…μ—μ„œ μƒνƒœλ₯Ό μ—…λ°μ΄νŠΈν•˜λŠ” 방법에 λŒ€ν•΄ μžμ„Ένžˆ μ•Œμ•„λ³΄μ„Έμš”.

λ‹€μ–‘ν•œ 제좜 νƒ€μž… μ²˜λ¦¬ν•˜κΈ° {/handling-multiple-submission-types/}

μ‚¬μš©μžκ°€ λˆ„λ₯Έ λ²„νŠΌμ— 따라 μ—¬λŸ¬ 제좜 μž‘μ—…μ„ μ²˜λ¦¬ν•˜λ„λ‘ 폼을 섀계할 수 μžˆμŠ΅λ‹ˆλ‹€. 폼 λ‚΄λΆ€μ˜ 각 λ²„νŠΌμ€ formAction ν”„λ‘œνΌν‹°λ₯Ό μ„€μ •ν•˜μ—¬ κ³ μœ ν•œ λ™μž‘ λ˜λŠ” λ™μž‘κ³Ό μ—°κ²°ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

μ‚¬μš©μžκ°€ νŠΉμ • λ²„νŠΌμ„ ν΄λ¦­ν•˜λ©΄ 폼이 제좜되고 ν•΄λ‹Ή λ²„νŠΌμ˜ 속성 및 λ™μž‘μœΌλ‘œ μ •μ˜λœ ν•΄λ‹Ή λ™μž‘μ΄ μ‹€ν–‰λ©λ‹ˆλ‹€. 예λ₯Ό λ“€μ–΄, 폼은 기본적으둜 κ²€ν† λ₯Ό μœ„ν•΄ λ¬Έμ„œλ₯Ό μ œμΆœν•˜μ§€λ§Œ formAction이 μ„€μ •λœ λ³„λ„μ˜ λ²„νŠΌμ΄ μžˆμ–΄ λ¬Έμ„œλ₯Ό μ΄ˆμ•ˆμœΌλ‘œ μ €μž₯ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

export default function Search() {
  function publish(formData) {
    const content = formData.get("content");
    const button = formData.get("button");
    alert(`'${button}' λ²„νŠΌμœΌλ‘œ '${content}'κ°€ λ°œν–‰λ˜μ—ˆμŠ΅λ‹ˆλ‹€.`);
  }

  function save(formData) {
    const content = formData.get("content");
    alert(`'${content}' μ΄ˆμ•ˆμ΄ μ €μž₯λ˜μ—ˆμŠ΅λ‹ˆλ‹€!`);
  }

  return (
    <form action={publish}>
      <textarea name="content" rows={4} cols={40} />
      <br />
      <button type="submit" name="button" value="submit">λ°œν–‰</button>
      <button formAction={save}>μ΄ˆμ•ˆ μ €μž₯</button>
    </form>
  );
}