#Dynamic Import Problem

1 messages · Page 1 of 1 (latest)

jagged iron
#

this works

import dynamic from 'next/dynamic'
function IconMapping(iconName: string = "ReportOutlined") {
let iconModule: string = "@mui/icons-material/ReportOutlined"
const IconComponent = dynamic(() => import("@mui/icons-material/ReportOutlined"))
return <IconComponent sx={{ fontSize: 36 }} className="text-white" />
}

But this doesnt

import dynamic from 'next/dynamic'
function IconMapping(iconName: string = "ReportOutlined") {
let iconModule: string = "@mui/icons-material/ReportOutlined"
const IconComponent = dynamic(() => import(iconModule))
return <IconComponent sx={{ fontSize: 36 }} className="text-white" />
}

why ?

fathom badgeBOT
#

Hi @jagged iron. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue you're experiencing is related to how Next.js handles dynamic imports. When you use a variable in the import statement, Next.js can't determine at build time what module to load, which leads to unexpected behavior or errors.

In the first example, you're using a static string in the import statement, which allows Next.js to correctly load the module at build time.

In the second example, you're using a variable (iconModule) in the import statement. Even though the variable is assigned a static string value, Next.js can't determine this at build time, which is why it doesn't work.

This issue has been reported in several GitHub issues related to Next.js, such as issue 49382 (https://github.com/vercel/next.js/issues/49382), issue 50527 (https://github.com/vercel/next.js/issues/50527), and issue 60698 (https://github.com/vercel/next.js/issues/60698).

A workaround for this issue is to create a mapping object for your components and use the dynamic import with the static paths. Here's an example:

import dynamic from 'next/dynamic';

const iconMapping = {
  ReportOutlined: dynamic(() => import('@mui/icons-material/ReportOutlined')),
  // Add other icons here...
};

function IconMapping(iconName: string = 'ReportOutlined') {
  const IconComponent = iconMapping[iconName];
  return <IconComponent sx={{ fontSize: 36 }} className="text-white" />;
}

In this example, iconMapping is an object where each key is the name of an icon, and each value is a dynamically imported component. This allows you to select different components at runtime while still using static paths in the import statements.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: