0

I am trying to perform dynamic page routing with react router, and thus far have had a little luck, but now I am trying to render the right Module component based on the parameter called {num} from below? how do I do this??

App.js

     <Route exact path="/" component={Menu}>
     <Route exact path="/Module/:num" component={Module} />

Menu.js

export default function Menu({ match }) {
  const modules = [
    {
      title: `Module1`,
      subtitle: "Introduction",
    },
    {
      title: `Module2`,
      subtitle: "Overview",
    }

  ];

  return (
          <div className={styles.menuGrid}>
            {modules.map((module, index) => (
              <div key={index} className={styles.menuCard}>
                <Link to={`/Module/${index + 1}`}>
                  <h2>{module.name}</h2>
                  <p>{module.subtitle}</p>
                </Link>
              </div>
            ))}
          </div>
  );
}

Module.js

import React from "react";
import Module1 from "./Pages/Module1";
import Module2 from "./Pages/Module2";

export default function Module({ match }) {
  const {
    params: { num },
  } = match;

  return (
    <div>
      {`<Module${num}/>`}<---not valid but my goal??
      ??RENDER MODULE1 OR 2 BASED ON {num}??
    </div>
  );
}
lache
  • 608
  • 2
  • 12
  • 29

1 Answers1

1

If you dynamically want to name your component,

import React from "react";
import Module1 from "./Pages/Module1";
import Module2 from "./Pages/Module2";

const components = {
  Module1,
  Module2
};

export default function Module({ match }) {
  const {
    params: { num },
  } = match;

  const MyModule = components["Module"+num]; 

  return (
    <div>
      <MyModule />
    </div>
  );
}

This will get the required component from components object and then simply render it.

Read more about it in official documentaion : https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime

Anuj Sharma
  • 409
  • 2
  • 8
  • Thank you, it is saying components not defined, does that mean I need to import them first? import {module1, module 2} from "./..." – lache Sep 08 '21 at 18:25
  • 1
    I have updated with components. It'll get the required component from components object and then simply render it. – Anuj Sharma Sep 09 '21 at 14:22