Challenges

Using Dynamic Imports

Add a Syntax Highligher

Our blog app has basic code displaying support. You can visit this blog post & see how it looks. Now it's time to add a proper syntax highlighter.

So, let's add the following NPM module:

yarn add react-syntax-highlighter

Then create a file called components/CodeWithSyntax.js and add the following content:

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { darcula } from 'react-syntax-highlighter/dist/cjs/styles/prism';

export default function CodeWithSyntax({ language, children }) {
    return (
        <SyntaxHighlighter style={darcula} language={language}>
            {children}
        </SyntaxHighlighter>
    )
}

Now open the file components/Code.js and replace the content with this:

import CodeWithSyntax from './CodeWithSyntax'

export default function Code({ children }) {
    const code = children.props.children;

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

Here we use the CodeWithSyntax component to render a code block.

šŸ’” If you wonder how we use this Code component inside markdown. Check the pages/post/[slug].js. Inside that, we ask our markdown component to use this Code component to render anything inside the HTML pre tag like this:

<Markdown
    options={{
        overrides: {
        Youtube: { component: Youtube },
        pre: { component: Code }
        }
    }}
    >
    {post.content}
</Markdown>

When you add a code block inside markdown, it will use the Code component to render it.


Now you can rerun your app and see how our blog post uses this syntax highlighter.

Q: But there's a problem. What's that?
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: