Submitting Forms `onChange`

김동현·2023년 3월 21일
0

React Router

목록 보기
24/31

UI를 위해 검색 필드에 값을 입력할 때마다 필터링이 되도록 해보자.

useSubmit 을 이용한다.

// 📄src/routes/root.jsx

// existing code
import {
  // existing code
  useSubmit,
} from "react-router-dom";

export default function Root() {
  const { contacts, q } = useLoaderData();
  const navigation = useNavigation();
  const submit = useSubmit();

  return (
    <>
      <div id="sidebar">
        <h1>React Router Contacts</h1>
        <div>
          <Form id="search-form" role="search">
            <input
              id="q"
              aria-label="Search contacts"
              placeholder="Search"
              type="search"
              name="q"
              defaultValue={q}
              onChange={(event) => {
                submit(event.currentTarget.form);
              }}
            />
            {/* existing code */}
          </Form>
          {/* existing code */}
        </div>
        {/* existing code */}
      </div>
      {/* existing code */}
    </>
  );
}

이제 키 입력시 폼 양식이 자동으로 제출된다.

submit() 의 매개변수를 보자.

event.currentTarget.form 을 전달했다.

currentTarget.form 은 이벤트 핸들러가 붙은 노드의 부모 폼 노드를 의미한다.

submit() 함수는 전달된 모든 폼을 serialize하여 submit한다.

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

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

0개의 댓글