Den Dribbles

Dynamic UIs Using Dynamic Imports, Next.js 10 and React State

December 09, 2020

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.

Setting up

We will use a simple create-next-app for this template.

# Create Next App template
npx create-next-app dynamic-imports-with-next
cd dynamic-imports-with-next
# Make components folder to house components
mkdir components
# Make file to house exported components
touch components/Hello.js

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.

In components/Hello.js, add the following:

export function Hello({ name }) {
  return <p>Hello, {name}!</p>
}

export function Goodbye({ name }) {
  return <p>Goodbye, {name}!</p>
}

The above is simple enough. <Hello name="world" /> would return <p>Hello, world!</p>. Similar for the Goodbye component.

Updating the index page

We are going to make adjustments to the home page.

import dynamic from "next/dynamic"
import { useState } from "react"

const DynamicHello = dynamic(() =>
  import("../components/hello").then(mod => mod.Hello)
)

const DynamicGoodbye = dynamic(() =>
  import("../components/hello").then(mod => mod.Goodbye)
)

function Home() {
  const [modules, setModules] = useState([])

  const addHello = () =>
    setModules([
      ...modules,
      { Component: DynamicHello, props: { name: "World!" } },
    ])

  const addGoodbye = () =>
    setModules([
      ...modules,
      { Component: DynamicGoodbye, props: { name: "Cruel World!" } },
    ])

  return (
    <div>
      {modules.map(({ Component, props }) => (
        <Component {...props} />
      ))}
      <button onClick={addHello}>Add hello!</button>
      <button onClick={addGoodbye}>Add Goodbye!</button>
    </div>
  )
}

export default Home

We are doing the following here:

  1. Adding some helper functions to dynamically import Hello and Goodbye.
  2. Using React state to store an array of components to dynamically import.
  3. Adding basic buttons to add the components for us.
  4. Adding closure functions that will make use of setModules function to set our dynamic components.
  5. Mapping out those modules in 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

Run 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:

Empty page

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

  1. Next.js Dynamic Import docs
  2. Completed project
  3. Completed code

Related Articles

December 02, 2020

Have you ever wanted to build a UI Component Library with TypeScript and React? This blog post will take you through a straightforward set up that uses the bare minimum to get a working component library that you can re-use across your different React projects.

November 16, 2020

This post will go through a simple example of setting up simple authentication with a user and password to your Next.js website.

November 08, 2020

This blog post will explore the new internationalised routing in Next.js 10 and how you can use this to your advantage with react-intl for React.js

November 08, 2020

This blog post will explore the new Next.js Image component for an optimised image experience on the web.

November 07, 2020

Learn how to create a test Stripe example, update that example and deploy to Vercel for a Stripe payment gateway, React 17, TypeScript 4 and Next.js 10

November 06, 2020

See a roundup of my look into Vercel's new analytics feature that you can enable on a Vercel project and see how I used GTMetrix to help push some numbers.

November 05, 2020

Learn how to deploy the base Next.js 10 app with the Vercel CLI and/or the Vercel GitHub Integration

November 04, 2020

Learn how to export static HTML from a Nextjs 10 project to host

October 28, 2020

Updating my previous post on using Create React App with Snowpack for the latest versions and NPM 7

September 30, 2020

A look into how you can run a cron job to self-destruct tweets

A personal blog on all things of interest. Written by Dennis O'Keeffe, Follow me on Twitter