Challenges

Using Dynamic Imports

Add a Loading Component

With the help from next/dynamic, we can add a loading component while Next.js loads the related JavaScript bundle. For that, open the components/Code.js file and apply these steps:

Remove the following line:

const CodeWithSyntax = dynamic(() => import('./CodeWithSyntax'))

Then add the following component:

function CodeFallback({ children, language }) {
    return (
        <pre>
            <code className="codeblock">
                {children}
            </code>
            <style jsx>{`
                pre {
                    color: hsl(0deg, 0%, 90%);
                    font-family: Consolas, Monaco, "Andale Mono", monospace;
                    direction: ltr;
                    text-align: left;
                    white-space: pre;
                    word-spacing: normal;
                    word-break: normal;
                    line-height: 1.5;
                    tab-size: 4;
                    hyphens: none;
                    padding: 1em;
                    margin: 0.5em 0px;
                    overflow: auto;
                    background: rgb(43, 43, 43);
                    font-size: 18px;
                    line-height: 27px;
                }
                code {
                    font-family: Consolas, Monaco, "Andale Mono", monospace;
                }
            `}</style>
        </pre>
    )
}

It's a fallback component to render the code block. It doesn't add colors to the code, but it has a similar look.

Then replace our existing default Code component with this:

export default function Code({ children }) {
    const code = children.props.children;
    const CodeWithSyntax = dynamic(
        () => import('./CodeWithSyntax'),
        {
            loading: () => (
                <CodeFallback>{code}</CodeFallback>
            )
        }
    )

    return (
        <CodeWithSyntax language={"javascript"}>
            {code}
        </CodeWithSyntax>
    )
}

As you can see, now we create the dynamic import inside the Code component itself. We also add an option called loading to pass a component to render while Next.js loads the related JavaScript bundle.


Now, let's do the previous experiment again:

  • Add above changes and run your app
  • Visit the homepage & reload it
  • Then click the first blog post with the title: "Blogpost with Code"

You will see the difference.


Here's a simple question for you.

Q: Why didn't we import the `CodeWithSyntax` code outside the `Code` component?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: