React-markdown is a robust and secure React component designed to render markdown strings into a React element tree. It is currently at version 10.1.0 and is actively maintained with regular minor and patch releases, and significant breaking changes occurring with major version bumps (e.g., v9, v10). A key differentiator is its commitment to security, rendering markdown safely without relying on `dangerouslySetInnerHTML`, thus preventing common XSS vulnerabilities by default. The component leverages the unified ecosystem, specifically remark for markdown parsing and rehype for HTML transformation, enabling extensive customization through a wide array of plugins. Developers can also provide their own React components to override default HTML element renderings, offering fine-grained control over the output. Unlike alternatives that might directly inject HTML or offer less flexibility, react-markdown builds a virtual DOM from a syntax tree, ensuring React efficiently updates only what has changed. It distinguishes itself from `react-remark` and `rehype-react` by being simpler for beginners, while MDX serves a different purpose for embedding JSX within markdown.
npm install react-markdownVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic usage of the `react-markdown` component to render a markdown string to React elements in a browser environment.
To apply styles or classes to specific HTML elements, use the `components` prop. For example, to style all `h1` elements: `<Markdown components={{ h1: ({node, ...props}) => <h1 className="my-h1-class" {...props} /> }} />`.Ensure your project's `package.json` specifies `"engines": { "node": ">=16" }` and update `react` and `@types/react` to version 18 or higher.Migrate your import statements from `const Markdown = require('react-markdown')` to `import Markdown from 'react-markdown'` and configure your project for ESM compatibility (e.g., by setting `"type": "module"` in `package.json`).Update your code to use the `urlTransform` prop, which takes the URL, its type ('image' or 'link'), and the value as arguments.Only use plugins that process raw HTML, such as `rehype-raw`, with markdown content from trusted sources, or ensure thorough sanitization of user-provided markdown before processing.
Change `const Markdown = require('react-markdown')` to `import Markdown from 'react-markdown'` and ensure your project is configured for ESM (e.g., by adding `"type": "module"` to `package.json` or using a bundler that handles ESM).Upgrade your React installation to React 18 or newer, along with its corresponding `@types/react` package. `npm install react@latest react-dom@latest @types/react@latest @types/react-dom@latest`.
To apply classes or styles to specific elements rendered by `react-markdown`, use the `components` prop to override the default HTML element renderer. For example: `<Markdown components={{ p: ({node, ...props}) => <p className="my-paragraph" {...props} /> }} />`.