skip to Main Content

I am new to NextJS and I am struggling to figure out the proper way of doing this. For this example I am trying to use WordPress and ACF’s Flexible Content module as a page builder of sorts.

On my index.js I am using getStaticProps and GraphQL query to check what Flexible Content modules are selected in WordPress, and would like to then turn each of those modules into a component.

I tried using the code below to loop through my module names and then import it as a component but it keeps throwing out an error "Unexpected token ). Expected this, import, async, function, [ for array literal, { for object literal, @ for decorator, function, class, null, true, false, number, bigint, string, regexp, `
| for template literal, (, or an identifier"

I am also not 100% if using "dynamic" is the correct way to do this, its just what I found as I researched how to do this.

  return (
    <Layout>
      <WebsiteJsonLd siteTitle={title} />
      <>
      {flexible.map( layout => {
          let layoutName = layout['__typename'].replace('Page_Acf_Flexiblecontent_', '');
          let FlexLayout = dynamic(() => import(''+layoutName));
          return (
              <h1>{layoutName}</h1>
              <FlexLayout />
          )
      })}
      </>
    </Layout>
  );

2

Answers


  1. Chosen as BEST ANSWER

    I was able to fix it! The code above actually works for the most part, it was just that the include path was incorrect. Changing it to mport(''+layoutName)); did the trick.

    I ended up not using this in the end though. Dynamic imports are not rendered server side so this is not great for my use case.


  2. From the Next.js docs:

    In import(‘path/to/component’), the path must be explicitly written. It can’t be a template string nor a variable. Furthermore the import() has to be inside the dynamic() call for Next.js to be able to match webpack bundles / module ids to the specific dynamic() call and preload them before rendering. dynamic() can’t be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to React.lazy.

    This means that:

    let FlexLayout = dynamic(() => import(''+layoutName));
    

    inside your component is an invalid statement. You can only dynamically import modules statically.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search