1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】 inputとuseStateを使ったバリデーションでコンソールエラー出た話。

Posted at

はじめに

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?