LoginSignup
7
8

More than 3 years have passed since last update.

Functional ComponentでもReact RouterのwithRouterを使う方法

Posted at

React RouterのwithRouterを、Class ComponentではなくFunctional Componentで使用する方法についてまとめます。

環境

  • react v16.10.1
  • react-router-dom v5.1.2

結論

  1. コンポーネント全体をwithRouterでラップし、引数としてpropsを渡す
  2. props.history.push("url")で遷移する
import React from 'react';
import { withRouter } from 'react-router-dom'

// コンポーネント全体をwithRouterでラップする
export const MyComponent = withRouter(props => {

    function handlePageMove() {
            // 遷移先のパスを設定
            props.history.push("/Home");
    }

    return (
        <>
            <button
                onClick={handlePageMove}
            >Go to Home!</button>
        </>
    );
});

補足

  • 親コンポーネントがある場合でも、子コンポーネントだけラップしたらOK
import React from 'react';
import { withRouter } from 'react-router-dom'

const MyComponent = withRouter(props => {
    // 上記と同じ
});

// 親コンポーネントはwithRouterでのラップは不要
export const ParentComponent = _ => {
    return (
        <>
            <MyComponent />
        </>
    );
}
7
8
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
7
8