管理画面系などたまーに下記の画像のように改行区切りで値を取得したい時があります。
そんなときは、サンプルコードのようにすればyupと組み合わせたときでも問題なく値を取得することが可能です。
import { NextPage } from 'next'; import { Controller, useForm } from 'react-hook-form'; import React, { ChangeEvent } from 'react'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; const schema = yup.object({ word: yup.array().required().of(yup.string().required()), }); type InputType = yup.InferType<typeof schema>; /** * TextAreaで改行区切りの値を扱う */ const TextArea: NextPage = () => { const { control, handleSubmit } = useForm<InputType>({ resolver: yupResolver(schema), }); const onSubmit = (data: InputType): void => console.log(data.word); const parseArray = (e: ChangeEvent<HTMLTextAreaElement>): string[] => { return e.target.value.split('\n'); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller control={control} name={'word'} defaultValue={[]} render={({ field: { onChange, value } }): JSX.Element => ( <textarea placeholder={'word1\nword2\nword3'} rows={5} onChange={(e): void => onChange(parseArray(e))} value={value?.join('\n')} /> )} /> <input type="submit" /> </form> ); }; export default TextArea;
ポイント
- おなじみのregisterではなく、Controllerとcontrolを使用する
- Controllerのnameでfield名を指定する
- renderでcomponentを返却する際に、onChangeで配列に変換し、valueで改行つきの文字列に変換する
- defaultValueで初期値を設定しないとエラーになる
まとめ
ユーザインターフェースがわかりにくいので、普段はあまり使われず、例が少なかったのでまとめてみました。