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
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.
From the Next.js docs:
This means that:
inside your component is an invalid statement. You can only dynamically import modules statically.