LoginSignup
0
0

More than 1 year has passed since last update.

react-hook-formの値を動的に書き換える

Posted at

発端

Autocompleteで候補を出し、クリックしたらフィールドの値を書き換える処理を行っていたが、Submitすると書き換わる前の値が残っていた。
見た目上は変わっているのでう~んと思ったが、

調べる

あった。
ガチガチに武装されているライブラリなため、カスタマイズする時は注意する。

propsにこのように渡し、

setValue={{ fn: setValue, name: 'hoge' }}

受け取り

AutoCompleteInputField.tsx
type AutoCompleteInputFieldProps = {
  // ...
  setValue: {
    fn: UseFormSetValue<any>;
    name: string;
    options?: SetValueConfig;
  };
};

実行した。

AutoCompleteInputField.tsx
const handleClickSuggestion = (event: React.MouseEvent<HTMLLIElement>) => {
  const newValue = event.currentTarget.getAttribute('data-value') ?? '';
  setValue.fn(setValue.name, newValue, setValue.options);
  setIsSuggestionsOpen(false);
};

propsの型定義をどうすれば厳密に出来るのかがよくわからなかったが、見なかったことにした。
任意の型を扱う書き方に対する理解が無さ過ぎる。。。

以上。

0
0
0

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
0
0