New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

markdown-parser-react

Package Overview
Dependencies
Maintainers
0
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

markdown-parser-react

A lightweight and configurable Markdown renderer for React and Next.js with syntax highlighting, definition lists, images, math and table support.

  • 2.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Markdown Parser React

A flexible and feature-rich React component for rendering Markdown content with customizable styling, extensive formatting options, and robust typings.

markdown-parser-react

npm npm bundle size downloads stars MIT LicenseCode Coverage

Features

  • 🚀 Full Markdown syntax support

  • 💅 Customizable styling with CSS classes and inline styles

  • 🔒 HTML sanitization

  • ♿ Accessibility support

  • 📱 Responsive image handling

  • 🎨 Syntax highlighting for code blocks

  • 📝 Task list support

  • 📊 Table support with alignment options

  • 🔗 Custom link handling

  • 🎯 Definition lists

  • 📑 Custom IDs for headers

  • 🔢 Nested list support

  • ➗ Supports Math Equations

Installation

Install Markdown Parser React using npm or yarn or pnpm:

npm  install  markdown-parser-react

# or

yarn  add  markdown-parser-react

# or

pnpm  add  markdown-parser-react

Basic Usage

The basic usage example demonstrates rendering a simple Markdown string:


import Markdown from "markdown-parser-react";

function MyComponent() {
  return <Markdown content="# Hello World
  This is **markdown** content." />;
}

Advanced Usage

In the advanced usage example, we see how you can configure the component with custom styling, classes, and additional features like task lists, code highlighting, and tables


import Markdown from "markdown-parser-react";

function BlogPost() {
  const markdownContent = `

# Welcome to My Blog

This is a _formatted_ paragraph with a [link](https://example.com).

- [x] Task 1

- [ ] Task 2

\`\`\`javascript

const hello = "world";

console.log(hello);

\`\`\`

| Column 1 | Column 2 |

|----------|----------|

| Cell 1 | Cell 2 |

`;

  return (
    <Markdown
      content={markdownContent}
      options={{
        customClasses: {
          headings: "blog-heading",

          paragraphs: "blog-paragraph",
        },

        customStyles: {
          headings: {
            color: "#2c3e50",

            fontFamily: "Georgia, serif",
          },
        },

        linkTarget: "_blank",

        sanitizeHtml: true,

        maxNestingLevel: 4,
      }}
      className="blog-content"
      asArticle={true}
      aria={{
        label: "Blog post content",

        describedBy: "blog-description",
      }}
    />
  );
}

Usage with Next.js

If you're using Next.js, you may encounter the "Text content does not match server-rendered HTML" error.

To avoid this issue, you can use next/dynamic to dynamically import the Markdown component, ensuring that it is only rendered on the client-side.

Here's how to use Markdown with Next.js:

import dynamic from "next/dynamic";

const Markdown = dynamic(
  () => import("markdown-parser-react").then((markdown) => markdown),

  {
    ssr: false,
  }
);

interface MyComponentProps {
  content: string;

  options?: {
    langPrefix?: string;
    linkTarget?: string; 
  };
}

export const MyComponent: React.FC<MyComponentProps> = ({
  content,
  options,
}) => {
  return (
    <div>
      <Markdown content={content} options={options} />
    </div>
  );
};


By using the next/dynamic function and passing ssr as false, we ensure that the Markdown component is only rendered on the client-side, preventing the mismatch error between server-rendered and client-rendered HTML in Next.js projects.

Configuration Options

Props

The MarkdownProps interface defines the properties that can be passed into the component. These props allow you to customize the behavior, appearance, and accessibility of the rendered Markdown.

PropTypeDescriptionExample
contentstringThe Markdown content to be rendered. This is the main content of the component.md<br># Hello World<br>**Bold text** [Link](https://example.com)
optionsParseOptions (optional)Configuration options for the Markdown parser.
classNamestring (optional)Additional CSS class names to be applied to the container.className="my-markdown"
styleReact.CSSProperties (optional)Custom styles to be applied to the container.style={{ backgroundColor: 'lightgray' }}
asArticleboolean (optional)Whether to wrap the content in an article element instead of a div. Recommended for semantic HTML when rendering full articles or blog posts. Defaults to false.asArticle={true}
idstring (optional)Custom ID to be applied to the container.id="blog-post-1"
aria{ label?: string, describedBy?: string } (optional)Additional accessibility attributes for the container. label is the accessible name, and describedBy references an element that provides more information.aria={{ label: 'Blog Content', describedBy: 'content-description' }}

ParseOptions

The ParseOptions interface provides configuration for parsing and rendering the Markdown content. It gives you the ability to customize how the content is parsed and displayed, including applying custom classes, styles, and controlling link behavior.

OptionTypeDescriptionExample
langPrefixstring (optional)Prefix for language-specific code block classes.langPrefix="language-"
customClassesCustomClasses (optional)Custom CSS classes for different Markdown elements.{ headings: 'custom-heading', paragraphs: 'custom-paragraph' }
customStylesCustomStyles (optional)Custom CSS styles for different Markdown elements.{ headings: { color: 'blue', fontFamily: 'Arial' } }
linkTarget`"_blank""_self""_parent"
sanitizeHtmlboolean (optional)Whether to sanitize HTML content to prevent XSS attacks. Defaults to false.sanitizeHtml={true}
maxNestingLevelnumber (optional)Maximum allowed nesting level for lists. Defaults to 6.maxNestingLevel={4}

Supported Markdown Features

Basic Formatting

  • Headers (H1-H6)

  • Bold and Italic text

  • Strikethrough

  • Links

  • Images

  • Blockquotes with citations

  • Ordered and unordered lists

  • Code blocks with syntax highlighting

Extended Features

  • Task lists with checkboxes

  • Tables with alignment options

  • Definition lists

  • Custom header IDs

  • Math expressions ($...$)

  • Superscript (^...^)

  • Subscript (~...~)

  • Highlighted text (==...==)

Code Block Example


```javascript

function hello() {
  console.log("Hello, world!");
}


```

Table Example


| Left | Center | Right |

|:-----|:------:|------:|

| L1 | C1 | R1 |

Customization

You can customize how the Markdown content is displayed by adjusting the appearance of different elements like headings, paragraphs, links, and more. Below are the options for customizing the styles and classes.

Custom Classes

You can pass your classNames to customClasses config inside the options object passed as props to the component

ElementTypeDescriptionExample
headingsstringCustom class for headings (H1-H6).headings:"custom-heading-class"
paragraphsstringCustom class for paragraphs.paragraphs:"custom-paragraph-class"
listsstringCustom class for lists (ordered and unordered).lists:"custom-list-class"
blockquotesstringCustom class for blockquotes.blockquotes:"custom-blockquote-class"
codeBlocksstringCustom class for code blocks.codeBlocks="custom-code-class"
tablesstringCustom class for tables.tables:"custom-table-class"
linksstringCustom class for links.links:"custom-link-class"
imagesstringCustom class for images.images:"custom-image-class"

Custom Styles

You can pass your styles to the customStyles property inside the option object.

ElementTypeDescriptionExample
headingsCSSPropertiesCustom styles for headings (H1-H6).headings:{{ color: 'blue', fontSize: '2em' }}
paragraphsCSSPropertiesCustom styles for paragraphs.paragraphs:{{ lineHeight: '1.5' }}
listsCSSPropertiesCustom styles for lists (ordered and unordered).lists:{{ marginLeft: '20px' }}
blockquotesCSSPropertiesCustom styles for blockquotes.blockquotes:{{ borderLeft: '4px solid gray' }}
codeBlocksCSSPropertiesCustom styles for code blocks.codeBlocks:{{ backgroundColor: 'black', color: 'white' }}
tablesCSSPropertiesCustom styles for tables.tables:{{ borderCollapse: 'collapse' }}
linksCSSPropertiesCustom styles for links.links:{{ textDecoration: 'underline' }}
imagesCSSPropertiesCustom styles for images.images:{{ maxWidth: '100%' }}

Default Styling

The component comes with default styles that can be imported:


import { defaultStyles } from "markdown-parser-react";

// In your global CSS or styled-components

const GlobalStyle = createGlobalStyle`

${defaultStyles}

`;


Accessibility

The component follows WCAG guidelines and provides:

  • Semantic HTML structure

  • ARIA attributes support

  • Keyboard navigation for interactive elements

  • Screen reader-friendly content structure

Browser Support

  • Chrome (latest)

  • Firefox (latest)

  • Safari (latest)

  • Edge (latest)

  • IE11 (with appropriate polyfills)

Contributing

Contributions are welcome! Please read our contributing guidelines for more information.

Issues

If you encounter any issues or have suggestions for improvements, please report them on the GitHub Issues page

Hire Me

If you need a freelance developer for your project, feel free to contact me at LinkedIn I have experience with React, Next.js, TypeScript, and Node.js, and I would be happy to discuss your project with you.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Happy Coding Everyone! 🧑🏽‍💻

Keywords

FAQs

Package last updated on 20 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc