React Hook Form と Styled Components を一緒に使いたい

2020.12.27

解決したいこと

環境

"react": "^16.13.1",
"react-hook-form": "^6.9.6",
"styled-components": "^5.1.1",
"typescript": "~3.7.2"

解決方法

コンポーネント側

type RefReturn =
  | string
  | ((instance: HTMLInputElement | null) => void)
  | React.RefObject<HTMLInputElement>
  | null
  | undefined;

type Props = React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>,
  HTMLInputElement> & {
  placeholder?: string
  name: string
  register: ({required}: { required?: boolean }) => RefReturn;
};

type Ref = (instance: HTMLInputElement | null) => void | React.RefObject<HTMLInputElement> | null | undefined

const FormInput = ({name, register, required, placeholder}: Props) => {
  return (
    <Input
      type="text"
      placeholder={placeholder}
      name={name}
      ref={register({required}) as Ref}
    />
  )
};

親コンポーネント

<FormInput
  type="password"
  placeholder="パスワード"
  name="password"
  register={register}
	required
/>

参考

Profile

shotaCoffee

shotaCoffee

Frontend Engineer

音楽とコーヒーが好きなフロントエンド中心のエンジニア

  • Twitter
  • GitHub