| 2024-03-30

Simple Markdown Rendering in Next.js

    Check out this simple tutorial on how to create a Markdown page using a server component in Next.js. See the app deployed here.

    By the way, check out my blog all about MDX at MDX Blog

    Assuming you have a Next.js project created, install react-markdown for parsing Markdown content.

    npm install react-markdown
    
    bash

    Create a React Server Component:

    Inside the app directory, create a new page.tsx

    import ReactMarkdown from "react-markdown";
    
    // Define CSS styles as a constant
    const styles = `
      /* Add your CSS styles here */
      h1 {
        font-size: 32px;
        font-weight: bold;
      }
      h2 {
        font-size: 24px;
        font-weight: bold;
      }
      p {
        font-size: 18px;
      }
      ul {
        list-style-type: square;
        margin-left: 20px;
      }
      li:hover {
        color: orange; /* Change color on hover */
        cursor: pointer; /* Optional: Change cursor to pointer on hover */
      }
    `;
    
    const content = `## My Markdown Content
    
    This is some **bold** text.
    
    - List item 1
    - List item 2
    - List item 3
    `;
    
    export default function MarkdownPage() {
      return (
        <div>
          {/* Use the styles constant */}
          <style>{styles}</style>
          <h1>My Markdown Blog</h1>
          <ReactMarkdown>{content}</ReactMarkdown>
        </div>
      );
    }
    
    jsx

    Start the Development Server: Run the following command in your terminal to start the Next.js development server:

    npm run dev
    
    bash

    That's it! You've created a Markdown page using a React server component in Next.js. You can modify the content variable with your Markdown content and customize the CSS styles as needed.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.