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>
  );
}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it is saying components not defined, does that mean I need to import them first? import {module1, module 2} from "./..."
I have updated with components. It'll get the required component from components object and then simply render it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.