1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[React]動的にコンポーネントを表示する

Last updated at Posted at 2020-03-01

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 で対応させたコンポーネントが表示される。

これよりもこっちの方がいいよ!とかあれば教えてもらえると嬉しいです!

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?