본문 바로가기

programming

react-hook-form 과 meterial-UI 함께 쓰기 (1) - TextField

react-hook-form은 material-UI 나 ant-D같은 외부 UI 라이브러리와 함께 사용할 수 있다.

 

그 중 가장 기본이 되는 TextField와 연결하는 방법을 정리해보려한다.

 

import TextField from '@material-ui/core/TextField';
import { useForm, Controller } from 'react-hook-form';

export default function App() {
  const { handleSubmit, control, formState: {errors} } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller 
        name="title" 
        control={control}
        defaultValue=""
        render={({ field }) => (
        <TextField
          {...field}
          id="title" 
          label="제목" 
          size="small" 
          variant="outlined"
          style={{width:"100%", marginBottom:"10px"}}
          InputLabelProps={{
            shrink: true,
          }}
          error={!!errors.title}
          helperText={errors.title ? errors.title?.message : ''}
        />
        )}/>
      <button type="submit">전송</button>
    </form>
  );
}

 

전달하는 속성들에 대해서 간략하게 정리해보자면

 

  • name : react-hook-form이 작성된 폼의 값들을 모아서 제출할 때, key 값으로 사용할 값이다. 유니크한 값으로 지정하도록 한다.
  • control : 상단의 useForm() 에서 선언한 control 인데, 간단하게 react-hook-form과 mui를 이어주는 용도라고 생각하자
  • defaultValue : 말 그대로 초기값인데, 없다면 빈스트링이라도 지정해두자. 지정하지 않으면 다음과 같은 warning 이 발생한다
index.js:1 Warning: A component is changing an uncontrolled input to be controlled. 
This is likely caused by the value changing from undefined to a defined value, which should not happen. 
Decide between using a controlled or uncontrolled input element for the lifetime of the component. 
More info: https://reactjs.org/link/controlled-components

 

  • render : 이제 내가 쓰고 싶은 UI 컴포넌트를 어떤식으로 렌더링 하겠다고, react-hook-form 에게 알려주는 부분이다다. 
    이 부분에서 원하는 컴포넌트를 (TextField)를 사용하면된다. TextField 컴포넌트 내부의 props들은 그냥 material-UI에서 제공하는 내용을 원하는대로 가져다 쓰면된다. 
    • error : mui 에서 기본적으로 제공하는 prop이지만 이를 react-hook-form에서 제공하는 validation 과 errors를 받아서 사용할 수 있다.
    • helperText : 역시 react-hook-form에서 던져주는 에러메시지를 받아서 사용할 수 있다.
      (기본적으로 영문 메시지가 뜨는데, 아래의 경우는 yup이라는 validation check용 라이브러리를 사용하여 에러메시지를 지정해준 경우이다.)

 

TextField의 경우 onChange 등 별도로 지정해 줄게 따로 없어서 간단하다.

 

다음 게시물(2)에서는 onChange 속성을 사용하는 ToggleButton에 대해서 알아보려한다.

https://tacit.tistory.com/42

 

react-hook-form 과 meterial-UI 함께 쓰기 (2) - ToggleButton

이전 게시물(1) - TextField 에 이어서 이번엔 ToggleButton 과 함께 사용하는 방법에 대해 정리해보려한다. CheckBox로 예시들이 몇개 구글에 나와있다. ToggleButton도 비슷한 맥락이다. import ToggleButton fr..

tacit.tistory.com