Dynamic Importing of an unknown component - NextJs

前端 未结 3 1601
心在旅途
心在旅途 2021-01-20 01:05

I want to load a component dynamically based on the route. I\'m trying to make a single page which can load any individual component for testing purposes.

However whe

相关标签:
3条回答
  • 2021-01-20 01:22

    I put dynamic outside of the component, and it work fine.

    const getDynamicComponent = (c) => dynamic(() => import(`../components/${c}`), {
      ssr: false,
      loading: () => <p>Loading...</p>,
    });
    
    const Test = () => {
      const router = useRouter();
      const { component } = router.query;
      
      const DynamicComponent = getDynamicComponent(component);
    
      return <DynamicComponent />
    }
    
    0 讨论(0)
  • 2021-01-20 01:38

    It happens because router.query is not ready and router.query.component is undefined at the very first render of dynamic page.

    This would print false at first render and true at the following one.

     console.log(path === '../../components/common/CircularLoader');
    

    You can wrap it with useEffect to make sure query is loaded.

    const router = useRouter();
    
    useEffect(() => {
      if (router.asPath !== router.route) {
        // router.query.component is defined
      }
    }, [router])
    

    SO: useRouter receive undefined on query in first render

    Github Issue: Add a ready: boolean to Router returned by useRouter

    0 讨论(0)
  • 2021-01-20 01:48

    I had the same issue like the thread opener. The Documentation describe, that it's not possible to use template strings in the import() inside dynamic:

    In my case it was also impossible to add an general variable with the path there...

    Solution

    I've found an easy trick to solve this issue:

    // getComponentPath is a method which resolve the path of the given Module-Name
    const newPath = `./${getComponentPath(subComponent)}`;
    const SubComponent = dynamic(() => import(''+newPath));
    

    All the MAGIC seems to be the concatenation of an empty String with my generated Variable newPath: ''+newPath

    Another Solution:

    Another Solution (posted by bjn from the nextjs-Discord-Channel):

    const dynamicComponents = {
      About: dynamic(() => import("./path/to/about")),
      Other: dynamic(() => import("./path/to/other")),
      ...
    };
    
    // ... in your page or whatever
    const Component = dynamicComponents[subComponent];
    return <Component />
    

    This example might be useful, if you know all dynamically injectable Components. So you can list them all and use it later on in your code only if needed)

    0 讨论(0)
提交回复
热议问题