next.jsmarkdownjavascript-marked

Marked does not render code snippet and table correctly


Markdown file

---
title: 'Testing Second Blog Post'
date: 'May 2 2022'
excerpt: 'This is the excerpt'
cover_image: '/images/posts/test.jpeg'
---

# Basics of Markdown

Markdown is the most popular markup language that can be used to format documents. It can be used to create _websites_,_ebooks_,_email_,_chats in discussions forums_.

## Topics

1. Paragraphs

    MD expects a full line space to show texts in a different line else it joins text in the same line.

2. Text decorations

    MD can write **bold** texts, ~~italiic~~ _italic_ texts

3. Headings
   No of #'s represent the type of heading. Github will automatically add id's to headings, so the text will be automatically linked.
    ## This is h2
    ### This is h3
4. Links

    [My Github](https://github.com/bhupendra1011 'all repos') account.[Bhupendra][1] github repo.

5. Images
   Images can be used just like links. ![Alt txt](img url)

    !["cat Img"](http://placekitten.com/200/200)

    Thumbnails images can also be used which links to larger image
    [<img src="http://placekitten.com/20/20">](http://placekitten.com/200/200)

6. Ordered and Unordered Lists

    Coding Best Practices:

    - Keep code DRY
    - Writing Unit Test cases
    - Checking cross-browser support

    Steps to merge branch:

    1. Create a branch from feature
    1. commit your changes
    1. push your changes
    1. raise a pull request

7. Code Blocks

    This is super helpful when posting any code snippet

    ```js
    const fn = () => alert('some fn');
    ```

    ```css
    .hide {
        display: none;
    }
    ```

    Also can show code difference

    ```diff
    var x = 10;
    - const counter = 0;
    + let counter = 0
    ```

8. Tables

    Tables can be generated with headings and text alignment option

    |  Stocks  | Price |
    | :------: | ----: |
    |   TCS    |   230 |
    | YES Bank |   500 |

Cool Tips

-   [Grammarly](https://marketplace.visualstudio.com/items?itemName=znck.grammarly) extension can eliminate typo and grammar mistakes
-   [ScreenTOGif](https://www.screentogif.com/) to record videos in GIF format
-   Upload GIF's to [giphy](https://giphy.com/) to embed them into blog posts.
-   [Stackedit](https://stackedit.io/) for Markdown Editing in Browser.

Result is web page

enter image description here

As the images are shown above, the code snippet and table do not render correctly, missing of styling. For example:

  1. Code block does not have background color
  2. Table is lacking of cell border

I'm using marked package and nextjs to render the markdown file. Below is the code to render it.

import type { GetStaticPaths, GetStaticProps, NextPage } from 'next';
import Head from 'next/head';
import styled from 'styled-components';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import WhatsApp from '../../components/WhatsApp';
import fs from "fs"
import path from 'path';
import matter from "gray-matter"
import { marked } from "marked"
import moment from 'moment';

const Main = styled.main`
  background: white;
    width: 95%;
    padding-top: 80px;
    max-width: 1126px;
    margin: auto;
    min-height: calc(100vh - 220px);
    
    .section-title {
        color: #000;
        font-size: 30px;
        font-weight: 700;
        text-align: center;
        margin: 0 auto;
    }

    .post_coverImage {
      width: 100%;
      height: 400px;

      img {
        width: 100%;
        height: 100%;
        max-width: 100%;
        max-height: 100%;
        object-fit: cover;
      }
    }

    .post_content {
      .post_body {
        margin: 50px auto 0;
        padding-bottom: 50px;
        width: 95%;
      }
    }

`;

interface PostHeroProps {
  image: string
}

const PostHero = styled.div<PostHeroProps>`
  width: 100%;
  height: 400px;
  background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url("${props => props.image}");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;

  .post_title {
    position: absolute;
    left: 20px;
    bottom: 0;
    width: 95%;

    h1 {
      color: white;
      margin: 0;
    }

    p {
      color: white;
    }
  }
`

interface PostProps {
    frontmatter: any,
    content: any,
    slug: string
}

const Post: NextPage<PostProps> = ({frontmatter: {title, date, cover_image}, content, slug}) => {
  return (
    <div style={{background: "#f2f2f2"}}>
      <Head>
        <title>Idealist Professionals - Igniting your Ideas</title>
        <meta name="description" content="About Idealist Pro" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Header activeMenu="blogs" />
      <Main>
        <PostHero image={cover_image}>
          <div className="post_title">
            <h1>{title}</h1>
            <p>{moment(date).format("MMMM DD, YYYY")}</p>
          </div>
        </PostHero>
        <div className="post_content">
          <div className="post_body">
            <div dangerouslySetInnerHTML={{__html: marked(content)}}></div>
          </div>
        </div>
        <WhatsApp />
      </Main>
      <Footer />
    </div>
  );
};

export default Post;

export const getStaticPaths: GetStaticPaths = async () => {
  const files = fs.readdirSync(path.join("public", "posts"));

  const paths = files.map((filename: string) => ({
    params: {
      slug: filename.replace(".md", "")
    }
  }))

  return {
    paths,
    fallback: false
  }
}

export const getStaticProps: GetStaticProps = async ({params}) => {
  const slug = params!.slug as string

  const markdownWithMeta = fs.readFileSync(path.join("public", "posts", slug + ".md"), "utf-8")

  const {data: frontmatter, content} = matter(markdownWithMeta)
  
  return {
    props: {
      frontmatter,
      content,
      slug
    }
  }
}


Solution

  • And, did you somehow add styles for the pre and table? As @Chris said it looks like your pre and table elements are rendering correctly, the error is in the styles, make sure you are adding styles for your elements in markdown, it is a bit difficult to control styles when working with md. You are using styled-components, but as a test try to add direct styles explicitly for the pre and table elements inside your global styles( globals.css ), if necessary force the style with !important "eye, as a test", and comment what happened.