URL の変更に合わせてコンポーネントを切り替えたくて、あれこれやってみたのでメモ。
react: 16.13.0
react-router-dom: 5.1.2
Route
// url から Component を決めて表示したいので slug を設定
<Route path='/:slug' component={MyComponent} />
Component
import React, { FC } from 'react';
import { useParams } from 'react-router-dom';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
import NotFound from './NotFound';
const MyComponent: FC = () => {
// Route で設定したパラメータを取得
const { slug } = useParams();
// URL に合わせてコンポーネントを設定。マッチしなかった場合用に NotFound を用意。
const components: { [key: string]: FC } = {
'component-a': ComponentA,
'component-b': ComponentB,
'not-found': NotFound,
};
// slug が存在してマッチすれば上で指定した Component を、そうでなければ NotFound をセット。
const ComponentName = (slug && components[slug]) || components['not-found'];
return <ComponentName />;
};
export default MyComponent;
これで、 URL に対して components
で対応させたコンポーネントが表示される。
これよりもこっちの方がいいよ!とかあれば教えてもらえると嬉しいです!