20
8

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 5 years have passed since last update.

Reactでページ遷移時にアラート・確認ダイアログなどを出す方法

Last updated at Posted at 2017-01-21

以下は react-router v3 系時代の情報です。

v4 以降ではこちらの <Prompt> を使うことによって実現できます。
https://reacttraining.com/react-router/core/api/Prompt


ページ遷移時に「○○は保存されていません。保存しますか?」的なメッセージを出したいことがあったので、実装方法を調べてみました。

結論から言うとrouterの "setRouteLeaveHook" 関数を使います。

公式ページにwithRouterを用いた例があります。
https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md

私はたまたま、子のコンポーネントにpropsとしてrouterを渡していたので、そのまま使ってみます。
"componentDidMount"内に以下の様なコードを入れます。

this.props.router.setRouteLeaveHook(current_route, this.alertOnLeave.bind(this));

一つ目の引数は今ユーザがいるRouteを表します。
二つ目の引数はhookとしての関数を表します。

hookする関数は下記のように文字列をReturnします。

public alertOnLeave(){
    if(this.state.memo_unsaved){
        return "メモが保存されていません。\n編集した内容は失われてしまいますが、このページを離れてもよろしいですか?";
    }
}

そうすると、ページを離脱する時にその文字列が入ったアラートが表示されます。

↓こんな感じ
image

20
8
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
20
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?