React Routerで複数のパスで同じコンポーネントを表示する:完全ガイド
React Routerで同じコンポーネントを複数のパス名で表示する方法
Route コンポーネントの path プロパティに複数のパスを指定する
<Route path={["/home", "/about"]} component={MyComponent} />
このコードは、/home
と /about
の両方のパスで MyComponent
コンポーネントを表示します。
Switch コンポーネントと Redirect コンポーネントを使用する
<Switch>
<Route exact path="/home" component={MyComponent} />
<Route exact path="/about" component={MyComponent} />
<Redirect from="/" to="/home" />
</Switch>
useParams フックを使用する
function MyComponent() {
const { path } = useParams();
// パス名に基づいて処理を行う
return (
<div>
<h1>{path}</h1>
</div>
);
}
<Route path={["/home", "/about"]} component={MyComponent} />
高階コンポーネントを使用する
const withPath = (Component) => {
const { path } = useParams();
return (
<div>
<h1>{path}</h1>
<Component />
</div>
);
};
const MyComponent = () => {
// 処理
return (
<div>
// コンポーネントの内容
</div>
);
};
<Route path={["/home", "/about"]} component={withPath(MyComponent)} />
- 複数のパスで同じコンポーネントを表示するだけであれば、
Route
コンポーネントのpath
プロパティに複数のパスを指定する方法は最も簡単です。 - パス名に基づいて処理を行う必要がある場合は、
useParams
フックを使用する必要があります。 - コンポーネントを再利用したい場合は、高階コンポーネントを使用する必要があります。
- この回答は、2024年3月21日時点の情報に基づいています。
- React Routerは常に更新されていますので、最新の情報を確認するようにしてください。
import React, { useState } from "react";
import { BrowserRouter as Router, Route, Switch, Redirect, useParams } from "react-router-dom";
function MyComponent() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<h1>カウント: {count}</h1>
<button onClick={handleClick}>カウントを増やす</button>
</div>
);
}
function App() {
return (
<Router>
<Switch>
{/* 1. `Route` コンポーネントの `path` プロパティに複数のパスを指定する */}
<Route path={["/home", "/about"]} component={MyComponent} />
{/* 2. `Switch` コンポーネントと `Redirect` コンポーネントを使用する */}
<Route exact path="/home" component={MyComponent} />
<Route exact path="/about" component={MyComponent} />
<Redirect from="/" to="/home" />
{/* 3. `useParams` フックを使用する */}
<Route path="/path/:id" component={PathComponent} />
{/* 4. 高階コンポーネントを使用する */}
<Route path="/with-path" component={withPath(MyComponent)} />
</Switch>
</Router>
);
}
function PathComponent() {
const { id } = useParams();
return (
<div>
<h1>パス名: /path/{id}</h1>
<p>ID: {id}</p>
</div>
);
}
const withPath = (Component) => {
const { path } = useParams();
return (
<div>
<h1>現在のパス: {path}</h1>
<Component />
</div>
);
};
export default App;
このコードをコピーして、Reactプロジェクトで実行してみてください。
他の方法
render プロパティを使用する
<Route path="/home" render={() => <MyComponent />} />
component プロパティと render プロパティを一緒に使用する
<Route path="/home" component={MyComponent} render={() => <MyComponent />} />
このコードは、/home
パスで MyComponent
コンポーネントを表示します。component
プロパティと render
プロパティを一緒に使用すると、コンポーネントに props を渡すことができます。
const withPath = (Component) => {
return (
<div>
<h1>現在のパス: {useParams().path}</h1>
<Component />
</div>
);
};
<Route path="/home" component={withPath(MyComponent)} />
- シンプルな方法であれば、
render
プロパティを使用する方法がおすすめです。 - コンポーネントに props を渡す必要がある場合は、
component
プロパティとrender
プロパティを一緒に使用する方法が必要です。
javascript reactjs path