Home > Software engineering >  How do I render the react components dynamically from imported module?
How do I render the react components dynamically from imported module?

Time:08-08

I am trying to render the React components dynamically based on the routes that are given in the URL.

canvas/index.tsx

export { default as CardGroup } from "./cards.example";

src/App.tsx

import React from "react";
import {
  useParams
} from "react-router-dom";
import * as Canvas from "./canvas";


const App: React.FC = () => {
    const params = useParams();
    const widgetName = (params.widgetName ?? '';
      return (
      <div className = "App" > 
      {< Canvas[widgetName] / >} // error here
      </div>
      );
    };

export default App;

I am not able to render the widget. It give me the following error.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof import("/Users/mypc/Code/atoms/src/canvas/index")'.

No index signature with a parameter of type 'string' was found on type 'typeof import("/Users/mypc/Code/atoms/src/canvas/index")'.

enter image description here

CodePudding user response:

Canvas[widgetName] isn't a valid React component. Compute the component value first as a local variable and then render it as JSX.

I suggest creating a local CanvasMap object so you can type it correctly for what is imported. You are creating a lookup object that uses string type keys and returns the React.FC component.

Example:

import React from "react";
import * as Canvas from "./canvas";
import { useParams } from "react-router-dom";

const CanvasMap: { [K: string]: React.FC<{}> } = {
  ...Canvas
};

const App: React.FC = () => {
  const { widgetName } = useParams();
  const CanvasComponent = CanvasMap[widgetName ?? "NotFound"];
  return (
    <div className="App">
      <CanvasComponent />
    </div>
  );
};

export default App;
  • Related