はじめに
inputタグの入力チェックで、コンソールにエラーが出たのでその解決方法。
出たエラーは以下
A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
問題
見た目や機能自体には特に影響はなく、コンソールにのみ表示されてました。
内容はundefined → 途中から数値に変化 しているよー。途中で数値(制御)に切り替わると「非制御→制御」になり警告出しますよーってことです。
わかるような、わからないような。
影響したコードは以下
const [time, setTime] = useState();
<input type="number" id="time" value={time} />
inputのtype属性をnumberにして、数値以外の受け入れを拒否したい訳です。
そこで、上記に書いてあるエラーが出てました。
解決方法
解決方法はシンプル
const [time, setTime] = useState('');
これだけです。useState()の引数に入れておいてあげるだけ。
<input type="number">でも event.target.value は 文字列で返ってくるため。空文字列を入れてあげるだけなんですね。
そのため、渡す値を数値型にするのではなく、値を計算などで扱いたい場合にparseInt()などで変換してあげるのが良いです。
おわりに
useStateの初期値問題がありますね。
参考
https://qiita.com/diescake/items/65ce4499ab8a70d029de
https://developer.mozilla.org/ja/docs/Web/HTML/Reference/Elements/input/number