LoginSignup
3
2

More than 5 years have passed since last update.

react-router v4でのJavaScriptでのリンクの作り方

Posted at

React-Router v4ではリンクの作成は、次のように行います。

<Link to='/my/link'>Link</Link>

これで、aタグが生成されます。ただし、実際の処理はhrefの値が使われているのではなく、onClickでhistoryにpushしてますね。あとは、React-Routerで画面遷移する方法としてはRedirectがあります。これも次のような感じでJSXで記述します。

<Redirect to='/my/link' />

リダイレクト

さて、ボタンで処理す場合など、JavaScriptの中から画面遷移したいケースがあります。この場合は、もっとも簡単なのがstateを使って遷移先を指定して、renderの中でリダイレクトさせるやり方です。

class MyComponent extends Component {
    state = { redirectUrl: null }

    redirectTo(target) {
        this.setState({ redirectUrl: target })
    }

    render() {
        if (this.state.redirectUrl) {
            return <Redirect to={this.state.redirectUrl} />
        }

        return <button onClick={() => {this.redirectTo('/my/link')}}>Link</button>
    }
}

ヒストリ

リダイレクトもいいですが、v4以前のようにhistoryにpushできます。 react-routerのIssue を見ていると、

Feel free to look at Links implementation and create your own with an async api.

とあります。Linkの実装を見ていると、次のように書けばとりあえずは動きます。

class MyComponent extends Component {
    static contextTypes = {
        router: PropTypes.shape({
            history: PropTypes.shape({
                push: PropTypes.func.isRequired,
                replace: PropTypes.func.isRequired,
                createHref: PropTypes.func.isRequired
            }).isRequired
        }).isRequired
    }

    render() {
        return <button onClick={() => {this.context.router.history.push('/my/link')}>Link</button>
    }
}

おわり

結局、どう書くのがセオリーなんでしょうね。history.pushのほうが自然な気がしますが、毎回contextTypesを書くのは不毛に見えます。

でわでわ

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