React Router v4 で過去へ未来へ!履歴操作の達人になる
React Router v4 で履歴を取得する方法
history
オブジェクトは、React Router v4 コンポーネントに 2 つの方法でアクセスできます。
withRouter
高階コンポーネントを使用して、コンポーネントにhistory
オブジェクトを props として渡すことができます。import React from 'react'; import { withRouter } from 'react-router-dom'; const MyComponent = (props) => { const { history } = props; // history オブジェクトを使用する return ( <div> <h1>{history.location.pathname}</h1> </div> ); }; export default withRouter(MyComponent);
history オブジェクトを使用して履歴を取得する
history
オブジェクトには、履歴に関する情報を取得するためのいくつかのプロパティとメソッドがあります。
- location プロパティ: 現在の場所に関する情報を含むオブジェクト。
pathname
プロパティ: 現在の URL のパス名search
プロパティ: 現在の URL のクエリ文字列state
プロパティ:history.push
またはhistory.replace
メソッドを使用して設定された状態オブジェクト
- length プロパティ: 履歴内のエントリの数を返す
- go メソッド: 履歴内の特定のエントリに移動する
- push メソッド: 履歴に新しいエントリを追加する
- replace メソッド: 履歴の現在のエントリを新しいエントリに置き換える
例
次の例では、history
オブジェクトを使用して、現在の場所のパス名を取得してログに記録する方法を示します。
import React from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const currentPath = history.location.pathname;
console.log(`現在のパス: ${currentPath}`);
return (
<div>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
この例では、history.location.pathname
プロパティを使用して、現在の URL のパス名を取得しています。取得したパス名は、コンソールにログ出力されます。
history
オブジェクトを使用して、React Router v4 で履歴を取得する方法を説明しました。history
オブジェクトには、履歴に関する情報を取得するためのいくつかのプロパティとメソッドがあります。これらのプロパティとメソッドを使用して、アプリケーションのナビゲーションを制御できます。
React Router v4 で履歴を取得する - サンプルコード
コンポーネントを作成する
まず、MyComponent
というコンポーネントを作成します。このコンポーネントは、useHistory
フックを使用して history
オブジェクトにアクセスし、現在の場所のパス名を取得してログに記録します。
import React from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const currentPath = history.location.pathname;
console.log(`現在のパス: ${currentPath}`);
return (
<div>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
アプリケーションを作成する
次に、MyComponent
コンポーネントを使用するアプリケーションを作成します。
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import MyComponent from './MyComponent';
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<MyComponent />} />
</Routes>
</BrowserRouter>
);
};
export default App;
このアプリケーションは、/
パスに MyComponent
コンポーネントをレンダリングします。
最後に、アプリケーションを実行します。ブラウザで http://localhost:3000/
にアクセスすると、コンソールに次の出力が表示されます。
現在のパス: /
この出力は、MyComponent
コンポーネントが現在の場所のパス名 (/
) を取得してログに記録していることを示しています。
その他の例
history
オブジェクトを使用して、履歴に関するその他の情報を取得することもできます。たとえば、次の例では、history.length
プロパティを使用して、履歴内のエントリの数を取得する方法を示します。
import React from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const numberOfEntries = history.length;
console.log(`履歴内のエントリの数: ${numberOfEntries}`);
return (
<div>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
import React from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const goToPreviousEntry = () => {
history.go(-1);
};
return (
<div>
<button onClick={goToPreviousEntry}>前のエントリに移動</button>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
この例では、history.go(-1)
メソッドを使用して、履歴内の前のエントリに移動します。このメソッドは、ボタンをクリックしたときに呼び出されます。
React Router v4 で履歴を取得するその他の方法
React Router v5.0 以降では、useLocation
フックを使用して location
オブジェクトにアクセスできます。location
オブジェクトには、現在の場所に関する情報が含まれています。
import React from 'react';
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
const location = useLocation();
const currentPath = location.pathname;
console.log(`現在のパス: ${currentPath}`);
return (
<div>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
この例では、useLocation
フックを使用して location
オブジェクトを取得しています。取得したオブジェクトを使用して、現在の場所のパス名を取得してログに記録しています。
withRouter 高階コンポーネントと location プロパティを使用する:
withRouter
高階コンポーネントを使用して、コンポーネントに history
オブジェクトを props として渡すことができます。その後、location
プロパティを使用して history
オブジェクトから現在の場所に関する情報にアクセスできます。
import React from 'react';
import { withRouter } from 'react-router-dom';
const MyComponent = (props) => {
const { location } = props;
const currentPath = location.pathname;
console.log(`現在のパス: ${currentPath}`);
return (
<div>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default withRouter(MyComponent);
react-router-dom
パッケージの Link
コンポーネントを使用して、ナビゲーションリンクを作成できます。Link
コンポーネントには、to
プロパティと onClick
プロパティがあります。to
プロパティを使用して、リンク先の URL を指定できます。onClick
プロパティを使用して、リンクがクリックされたときに実行する関数を指定できます。
import React from 'react';
import { Link } from 'react-router-dom';
const MyComponent = () => {
return (
<div>
<Link to="/">ホームへ戻る</Link>
{/* コンポーネントのレンダリング */}
</div>
);
};
export default MyComponent;
この例では、Link
コンポーネントを使用して /
パスへのリンクを作成しています。リンクがクリックされると、history.push('/')
メソッドが呼び出され、現在の場所が /
に変更されます。
React Router v4 で履歴を取得するには、さまざまな方法があります。上記以外にも、history.replace
メソッドや history.createHref
メソッドなど、history
オブジェクトには他にも多くのプロパティとメソッドがあります。
これらの方法を組み合わせて、アプリケーションのニーズに合った方法で履歴を取得できます。
reactjs react-router