LoginSignup
2
3

More than 5 years have passed since last update.

処理待ち中にボタンの上にSpinnerを表示する(React版)

Last updated at Posted at 2017-09-20

これは、初心者歓迎!Reactとvte.cxでWebアプリケーションを作成する#2<動作確認〜ソース解説>の説明に使う予定の資料です。

今回は、Reactの理解のために、処理待ち中にボタンの上にSpinnerを表示する実装について説明します。
こんな感じで、メールを送信するボタンを押すと、クルクル回るスピナーを表示するものです。

develop.gif

ソース解説

パスワードリセット画面のソースの一部を抜粋したものが以下になります。

ロジックの部分

まず、stateにisLoadingを追加します。(初期値はfalse)
サーバアクセス時に、trueにし、実行後にfalseにするだけです。

constructor() {
    this.state = { isLoading: false }
}
handleSubmit(e:InputEvent){
    this.setState({isLoading:true})
    axios({
         ・・・
    }).then( () => {
        this.setState({isLoading:false})
    }).catch((error) => {
        this.setState({isLoading:false})
    }
}

JSXの部分

JSXでは、isLoadingがfalseのときに「メールを送信する」を、trueのときに、スピナーと「送信中」を表示するようにします。disabledを指定すると送信中はボタンを押せなくなります。

<Button type="submit" className="btn btn-lg login_form__btn--submit" disabled={this.state.isLoading}>
{this.state.isLoading ? <span><span className="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> 送信中</span> : 'メールを送信する'}
</Button>

CSSの部分

スピナーは、イメージ画像ではなく、css3のanimationが使われています。
参考:Animated button

.glyphicon-refresh-animate {
    -animation: spin .7s infinite linear;
    -webkit-animation: spin2 .7s infinite linear;
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg);}
    to { -webkit-transform: rotate(360deg);}
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg);}
    to { transform: scale(1) rotate(360deg);}
}
2
3
1

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
3