Dynamic UIs Using Dynamic Imports, Next.js 10 and React State
As I continue my posts looking into Next.js 10, we have now arrived at dynamic imports.
Dynamic imports are incredible and can be such an important tool in the toolkit.
In this post I will show you can dynamically create UIs based on React State using dynamic imports, Next.js 10 and React State.
We will use a simple
create-next-app for this template.
Adding the components to be dynamically exported
In this example, I will extend off the named exports example given on the Next.js docs.
We will extend it by enabling the components exported to take props.
components/Hello.js, add the following:
The above is simple enough.
<Hello name="world" /> would return
<p>Hello, world!</p>. Similar for the
Updating the index page
We are going to make adjustments to the home page.
We are doing the following here:
- Adding some helper functions to dynamically import
- Using React state to store an array of components to dynamically import.
- Adding basic buttons to add the components for us.
- Adding closure functions that will make use of
setModulesfunction to set our dynamic components.
- Mapping out those
modulesin the returned JSX.
I am keeping things incredibly simple above, so the helper closure functions will set the name props for us but you can be more creative in your own work.
Seeing the dynamic imports in action
npm run dev from the command line to start our app in development mode.
Head to the localhost page and you will see the following:
The page itself is pretty bare, but once we start clicking some buttons we can see the magic in action!
After pressing buttons
It took us only a few lines, but we can see how components can be required at run time. It is super impressive what you can do with dynamic imports and hopefully you will begin to make the most of using this feature.
Resources and further reading
See how you can get started with the VSCode debugger for Node.js applications
1,200+ PEOPLE ALREADY JOINED ❤️️
Get fresh posts + news direct to your inbox.
No spam. We only send you relevant content.