2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】空白文字を削除するtrim() メソッド

Posted at

はじめに

現在React×TypeSript学習を行っています。
Udemyの下記の講座を受講しています。

問題

下記の画面にて、「ユーザーIDが入力されていないときはログインボタンを押下できない処理」を実装しました。

image.png

ログインボタンのタグで、「userIdが空文字のときにdisabledがtrueになる」処理としてdisabled={userId === ""}と書いたのですが、ユーザーIDを入力しなくてもログインボタンが押せてしまいました。

tsx
const onClickLogin = () => login(userId);
       
      //~中略~
                    <PrimaryButton
                        disabled={userId === ""}
                        loading={loading}
                        onClick={onClickLogin} >ログイン
                    </PrimaryButton>

解決方法

trim() メソッドを使いました。

tsx

const onClickLogin = () => {
        if (userId.trim() !== "") {
            login(userId);
        }
    };

    //~中略~
                    <PrimaryButton
                        disabled={userId === ""}
                        loading={loading}
                        onClick={onClickLogin} >ログイン
                    </PrimaryButton>

trim() メソッドとは?
文字列の両端から空白文字を削除するメソッドです。

おわりに

修正前のコード
userId === "" の条件は、ユーザーが何も入力せずにログインボタンを押した場合にのみdisabledがtrue となり、ログインボタンが無効になります。しかし、ユーザーがスペースや改行などの空白文字だけを入力した場合には、disabledがfalse となり、ログインボタンが有効になってしまいます。

修正後のコード
trim() メソッドを使用して余分な空白や空白文字を削除することで、ユーザーが間違ってスペースを入力したりしても、ログインが無効になります。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?