react-hook-form의 handleSubmit으로 제출 시 새로고침을 하지 않는 장점이 있습니다.
e.preventDefault() 기능을 자체적으로 지원한다고 보면 됩니다.
이 기능을 활용하여 검색창을 만들어보았습니다!
목차
1. UI
2. 구현 (react-hook-form의 handleSubmit 활용)
3. 결과화면
4. 개발 과정에서 발생한 문제
1. UI
2. 구현
위와 같은 검색창을 만들기 위해 다음과 같이 필요합니다.
- input 태그
- svg 아이콘 1 => 제출(엔터 눌렀을 때도 동작)
- svg 아이콘 2 => 빈 값으로 제출
이 3개의 태그를 크게 감쌀 form 태그가 필요합니다.
import SvgIcon from "@/components/Icon/SvgIcon";
import useQueryString, { DEFAULT_KEYWORD } from "@/hooks/useQueryString";
import { useForm } from "react-hook-form";
import styled from "styled-components";
interface Props extends React.InputHTMLAttributes<HTMLInputElement> {}
interface FormInput {
keyword: string;
}
const Search = ({ ...props }: Props) => {
const { register, handleSubmit, setValue } = useForm<FormInput>();
const { setKeyword, removeKeyword } = useQueryString();
const onSubmit = (data: FormInput) => {
setKeyword(data.keyword);
};
const onDelete = () => {
setValue("keyword", DEFAULT_KEYWORD);
removeKeyword();
};
return (
<SearchStyle onSubmit={handleSubmit(onSubmit)}>
<input {...register("keyword")} {...props} />
<SvgIcon
name="search"
width="22px"
height="22px"
stroke="#777C89"
className="search__btn"
// type="submit"
onClick={handleSubmit(onSubmit)}
/>
<SvgIcon
name="xCircle"
width="16px"
height="16px"
fill="#777C89"
stroke="white"
className="delete__btn"
onClick={onDelete}
/>
</SearchStyle>
);
};
3. 결과 화면
4. 개발 과정에서 발생한 문제
위의 코드에서 주석 처리된 부분을 잘 살펴보면 사용자 지정 SvgIcon 컴포넌트 안의 프롭스가 있습니다.
type="submit"은 input 태그의 속성이며, 주로 form 태그와 같이 사용합니다. But 제가 만든 SvgIcon 컴포넌트는 input 속성을 고려하지 않고 만든 컴포넌트이므로, type="submit"을 프롭스로 받을 수 없습니다.
제가 생각한 해결 방법은 다음과 같습니다.
onClick으로 handleSubmit을 호출하여 돋보기 아이콘을 클릭했을 때 "제출"할 수 있도록 만들었습니다.
이로써 엔터를 눌렀을 때와 마찬가지고 돋보기 아이콘을 클릭했을 때도 handleSubmit으로 "제출"하여 새로고침을 제거할 수 있었습니다!
'코치코치' 카테고리의 다른 글
white-space: pre-line 스타일 추가로 줄바꿈 인식 (0) | 2024.11.30 |
---|---|
코치 폴더 구조 리팩토링 (Feat. cursor ai) (0) | 2024.11.24 |
주소로 장소 표시하기 (Feat. Kakao Maps API) (2) | 2024.11.17 |
정보구조도(IA) (2) | 2024.10.25 |
SVG 공통 컴포넌트 사용하기 (0) | 2024.10.20 |