TIL: react-hook-form | Get Started - 220927

Lumpen·2022년 9월 26일
0

TIL

목록 보기
146/242

react-hook-form

  • Less code. More performant

  • Isolate Re-renders

  • Subscriptions

  • Faster Mounting

위와 같은 장점 외에도
react web과 react-native 모두 호환되고,
typescript에 대한 문서가 잘 정리되어 있다는 장점이 있다

react-hook-form은 렌더링 최적화가 잘 되어 있기 때문에
useEffect() 등을 사용할 때 생각한데로 동작하지 않을 수 있어 유의해야 한다

import React from 'react';
import {useForm, Controller, SubmitHandler} from 'react-hook-form';
import {TextInput, View, Button} from 'react-native';

type Inputs = {
  name: string;
};

const LoginForm = () => {
  // control은 form 상태를 저장하는 변수
  // handleSubmit은 form을 제출할 때 사용
  const {control, handleSubmit} = useForm<Inputs>();
  const onSubmit: SubmitHandler<Inputs> = data => console.log(data);
  
  return (
    <View>
      <Controller
        control={control}
  		rules={{
            required: true,
            pattern: {
            value: PHONE_NUMBER_REGEXP,
            message: '입력이 틀렸습니다.',
          },
        }}
        {/* 
        	rules: 유효성 검사
        	defaultValue: 폼이 입력되지 않았을 때의 기본값
            render: 실제 렌더링 될 TextInput을 생성하는..?
        */}
        name="name"
        defaultValue=""
        render={({field: {onChange, value}}) => {
          return (
            <TextInput
              onChangeText={onChange}
              value={value}
              placeholder="hi"
              style={{
                borderWidth: 0.5,
                borderColor: '#aaa',
                height: 20,
                borderRadius: 3,
              }}
            />
          );
        }}></Controller>
      <Button
        onPress={handleSubmit(data => onSubmit(data))}
        title="Submit"></Button>
    </View>
  );
};

export default LoginForm;
profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글