React-Hook-Form

김현민·2021년 6월 2일
0

React

목록 보기
17/30
post-thumbnail
  1. 모듈

    actions / index. js

    reducers / todos.js, index.js , ...

    1. counter 모듈

      1. 액션타입 - 모듈이름/액션명
      2. 액션 생성함수
      3. 초기상태 선언
      4. 리듀서 선언
    2. todos 모듈

      1. 액션타입
      2. 액션생성함수
      3. 초기상태선언
      4. 리듀서 선언
    3. 모듈 합치기

      1. modules/ index.js -- rootReducer
        • combineRedeucers({todos, counter})
    4. store 생성

      • src / index.js
        • const store = createStore(rootReducer)
    5. 리액트 프로젝트에 적용 (react-redux)

      • <Provider store={store}>
            <App/>
        </Provider>

React - Hook - Form

1. control

const {control} = useForm();

해당 객체에 직접 프로퍼티를 넣지 말것. 오직 내부에서만 사용한다.

2. register

{...register("username")}

input에서 값을 불러오기 위한 함수

옵션으로 validation이 가능하다.

값을 확인하기 위한 방법 ? console.log(watch())

3.handleSubmit

함수를 인자로 받는다. (handleSubmit(함수))

이 함수에 data라는 인자를 넘겨줌

export default function App(){
    const {register, handleSubmit} = useForm();
    
    // =========== 인자로 들어갈 놈 ============ 
        const onSubmit = (data) => {
            console.log(data);
        }
    // ======================================
    
    return (
      <div className="App">
      <form onSubmit={handleSubmit(onSubmit)}>
        <input type="text" placeholder="username" {...register("username")} />
        <input type="submit" />
      </form>
    </div>
    )
}

4. 실시간 유효성 검사 (mode)

useForm({mode : 'onChange'});

이렇게 하면 react hook form 이 실시간 유효성 검사를 해준다.

import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";

export default function App() {
  const { register, handleSubmit, errors } = useForm({ mode: "onChange" });
  const onSubmit = (data) => {
    console.log(data);
  };
  const onError = (error) => {
    console.log(error);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmit, onError)}>
        <input
          type="text"
          placeholder="username"
          {...register("username", {
            minLength: {
              value: 5,
              message: "Username must be longer than 5 characters"
            }
          })}
        />
        <input type="submit" />
      </form>
      {errors && <h1>{errors?.username?.message}</h1>}
    </div>
  );
}

styled components

  • theme provieder
    • context API기반
    • props로 전달받아서 사용 가능하다.

context API ?

  • 리액트 내장 기능
  • dependency 없기 가볍게 사용 가능
  • 리액트는 미들웨어 추가 가능

redux vs contextAPI

  1. 전역상태의 context
  2. 그걸 제공하는 provider
  3. 상태를 받아 사용하는 consum
profile
Jr. FE Dev

0개의 댓글

Powered by GraphCDN, the GraphQL CDN