[Fend] react-hook-form > 폼 요소 컴포넌트 만들기

oaksusu·2024년 5월 16일
0

Fend

목록 보기
1/5
post-thumbnail

1. input 컴포넌트 만들기

1-1. 고민 포인트

1. props로 전달하는 값들이 너무 많거나, 각각 다 다를텐데 어떻게 전달해야 효율적일까?

2. react-hook-form의 register함수나, errors들도 전달이 가능한걸까?

1-2. 해결하기

1. React.DetailedProps 사용하기

1) HTMLAtrributes의 파생타입을 제네릭으로 받아서 해당 타입을 반환
태그 속성들의 타입들을 가져올수있음

import {InputHTMLAttributes, DetailedHTMLProps} from "react";

type Props = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>

2) 원래의 input 속성이 아니지만, input 컴포넌트 만들때 필요한 값들이 있을경우
별도의 타입을 선언하고 Props 뒤에 & 연산자를 사용해서 붙여줌
(사용할땐 props로 접근하기 예: props.label)

type InputValue = { // 추가로 전달하고 싶은 속성들은 여기서
  label: string
}

React.forwardRef<HTMLInputElement, Props & InputValue>((props, ref) => { // type들 사용 이유 
type 사용 이유
  • HTMLInputElement : ref 때문에 필요함
  • Props : input 속성들
  • InputValue : 추가로 전달할 속성들

2. register함수는 여러 속성들이 담긴 객체를 반환하는데,

그 중에서 ref도 input 컴포넌트에 전달되어야 함.

1) React.forwardRef를 사용해줘야 함.

함수형 컴포넌트에서는 기본적으로 ref를 자식 컴포넌트에게 props로 넘겨줄수 없다고 한다.
💡 그렇지만!!
React.forwardRef는 ref를 자식 컴포넌트에 전달할 수 있게 해주는 함수다.

2) type은 HTMLInputElement으로 지정해줘야 함

1-3. 추가로 알게 된 내용

1. react에서 form을 다루는 2가지 방법 : 비제어 컴포넌트 / 제어 컴포넌트

  • 비제어 컴포넌트: ref를 통해 DOM에 접근해서 조작하기 때문에 리렌더링 발생 X, form을 제출할때 접근
  • 제어 컴포넌트: 입력할때마다(ex. onChange) 상태 변경이 되고 리렌더링 발생

2. enum을 사용을 반드시 지양해야하는 걸까?

나는 enum을 만들고 사용했다면 tree-shaking될 필요가 없고 써도 되는거 아닐까라는 생각이 들었고,
line의 기술 블로그도 보고, 다른 의견의 블로그도 보았을때 enum을 마냥 지양하는게 답은 아니겠다 생각을 했다.

3. 컴포넌트 만들면서 type들도 따로 파일에 관리하려고 export, import시켰는데

enum에서 에러가 났었음

에러내용 : 'QuestionList' cannot be used as a value because it was imported using 'import type'.ts(1361)

해결한 방법
  1. export 할때
export {QuestionList}; // enum인 경우 그냥 export
export type {FormValue}; // enum을 제외한 나머지 타입들은 export type
  1. import 할때
import { QuestionList } from "../../types/join"; // enum인 경우 그냥 export
import type { FormValue } from "../../types/join"; // enum을 제외한 나머지 타입들은 export type

2. 적용

import React, {InputHTMLAttributes, DetailedHTMLProps} from "react";

type Props = DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>; // 1번 해결점

const Input = React.forwardRef<HTMLInputElement, Props>((props, ref) => {// 2번 해결점
  return <input ref={ref} {...props}/>;
});
export default Input;

참고

react-hook-form + yup + forwardRef()를 이용한 input 컴포넌트 제작하기, 오류해결
React-Re-rendering-과-최적화
Carrot-market-정복-노트-6-React-Hook-Form
⭐️리액트에서 기본 컴포넌트를 만들때
⭐️자식-컴포넌트의-ref에-접근하는-법
⭐️'타입스크립트 enum 을 사용하지 않는 방법' 을 사용하지 않는게 좋은 이유

profile
삐약

0개의 댓글

관련 채용 정보