3

I need to import component based on the name I get from backend. Since I can spread and get the component name from the props only, is it fine to use dynamic import inside the component? Does it have any downsides?

import React from "react";
import Link from "next/link";
import dynamic from "next/dynamic";

const DropdownItem = ({ iconName }) => {
  const Icon = dynamic(() => import(`components/icons/${iconName}`));

  return (
    <Link href="/" passHref>
       <Icon />
    </Link>
  );
};

export default DropdownItem;
Serhii Zharkov
  • 496
  • 5
  • 22
  • This is perfect. Just use a loader state for loading the icon https://nextjs.org/docs/advanced-features/dynamic-import – Monzoor Tamal Jul 26 '20 at 20:14
  • 2
    I think there is a little downside to ues `dynamic` inside of component, you can reference of [Dynamic Importing of an unknown component - NextJs](https://stackoverflow.com/questions/62942727/dynamic-importing-of-an-unknown-component-nextjs) – bcjohn Jul 27 '20 at 13:06

0 Answers0