LoginSignup
1
0

More than 1 year has passed since last update.

無駄なレンダリングなしで submit できる react-hook-form

Last updated at Posted at 2021-02-05

React でフォーム画面を作るときに便利だった react-hook-form のメモ。

親コンポーネント
import React from 'react';
import { useForm } from 'react-hook-form';
import D from './D';
import E from './E';
import F from './F';

const C = () => {

  const { register, handleSubmit, watch, errors } = useForm();

  const onSubmit = (data) => {
    console.log(data); // submit時のフォームの値が入っている
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Button type="submit">送信</Button>

      {/* 子コンポーネント */}
      <D name="name" register={register} />
      <E name="mail" register={register} />
      <F name="open" register={register} />
    </form>
  )
}
export.default C;
子コンポーネント
import React from 'react';

const D = props => {
  return (
    <input type="text" name={props.name} ref={props.register} />
  )
}
export.default D;
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0