Giter Site home page Giter Site logo

react-markdown's Introduction

react-markdown

Build Coverage Downloads Size Sponsors Backers Chat

React component to render markdown.

Feature highlights

  • safe by default (no dangerouslySetInnerHTML or XSS attacks)
  • components (pass your own component to use instead of <h2> for ## hi)
  • plugins (many plugins you can pick and choose from)
  • compliant (100% to CommonMark, 100% to GFM with a plugin)

Contents

What is this?

This package is a React component that can be given a string of markdown that it’ll safely render to React elements. You can pass plugins to change how markdown is transformed and pass components that will be used instead of normal HTML elements.

When should I use this?

There are other ways to use markdown in React out there so why use this one? The three main reasons are that they often rely on dangerouslySetInnerHTML, have bugs with how they handle markdown, or don’t let you swap elements for components. react-markdown builds a virtual DOM, so React only replaces what changed, from a syntax tree. That’s supported because we use unified, specifically remark for markdown and rehype for HTML, which are popular tools to transform content with plugins.

This package focusses on making it easy for beginners to safely use markdown in React. When you’re familiar with unified, you can use a modern hooks based alternative react-remark or rehype-react manually. If you instead want to use JavaScript and JSX inside markdown files, use MDX.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install react-markdown

In Deno with esm.sh:

import Markdown from 'https://esm.sh/react-markdown@9'

In browsers with esm.sh:

<script type="module">
  import Markdown from 'https://esm.sh/react-markdown@9?bundle'
</script>

Use

A basic hello world:

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'

const markdown = '# Hi, *Pluto*!'

createRoot(document.body).render(<Markdown>{markdown}</Markdown>)
Show equivalent JSX
<h1>
  Hi, <em>Pluto</em>!
</h1>

Here is an example that shows how to use a plugin (remark-gfm, which adds support for footnotes, strikethrough, tables, tasklists and URLs directly):

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

const markdown = `Just a link: www.nasa.gov.`

createRoot(document.body).render(
  <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown>
)
Show equivalent JSX
<p>
  Just a link: <a href="http://www.nasa.gov">www.nasa.gov</a>.
</p>

API

This package exports the following identifier: defaultUrlTransform. The default export is Markdown.

Markdown

Component to render markdown.

Parameters
Returns

React element (JSX.Element).

defaultUrlTransform(url)

Make a URL safe.

Parameters
  • url (string) — URL
Returns

Safe URL (string).

AllowElement

Filter elements (TypeScript type).

Parameters
Returns

Whether to allow element (boolean, optional).

Components

Map tag names to components (TypeScript type).

Type
import type {Element} from 'hast'

type Components = Partial<{
  [TagName in keyof JSX.IntrinsicElements]:
    // Class component:
    | (new (props: JSX.IntrinsicElements[TagName] & ExtraProps) => JSX.ElementClass)
    // Function component:
    | ((props: JSX.IntrinsicElements[TagName] & ExtraProps) => JSX.Element | string | null | undefined)
    // Tag name:
    | keyof JSX.IntrinsicElements
}>

ExtraProps

Extra fields we pass to components (TypeScript type).

Fields

Options

Configuration (TypeScript type).

Fields
  • allowElement (AllowElement, optional) — filter elements; allowedElements / disallowedElements is used first
  • allowedElements (Array<string>, default: all tag names) — tag names to allow; cannot combine w/ disallowedElements
  • children (string, optional) — markdown
  • className (string, optional) — wrap in a div with this class name
  • components (Components, optional) — map tag names to components
  • disallowedElements (Array<string>, default: []) — tag names to disallow; cannot combine w/ allowedElements
  • rehypePlugins (Array<Plugin>, optional) — list of rehype plugins to use
  • remarkPlugins (Array<Plugin>, optional) — list of remark plugins to use
  • remarkRehypeOptions (Options from remark-rehype, optional) — options to pass through to remark-rehype
  • skipHtml (boolean, default: false) — ignore HTML in markdown completely
  • unwrapDisallowed (boolean, default: false) — extract (unwrap) what’s in disallowed elements; normally when say strong is not allowed, it and it’s children are dropped, with unwrapDisallowed the element itself is replaced by its children
  • urlTransform (UrlTransform, default: defaultUrlTransform) — change URLs

UrlTransform

Transform URLs (TypeScript type).

Parameters
  • url (string) — URL
  • key (string, example: 'href') — property name
  • node (Element from hast) — element to check
Returns

Transformed URL (string, optional).

Examples

Use a plugin

This example shows how to use a remark plugin. In this case, remark-gfm, which adds support for strikethrough, tables, tasklists and URLs directly:

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

const markdown = `A paragraph with *emphasis* and **strong importance**.

> A block quote with ~strikethrough~ and a URL: https://reactjs.org.

* Lists
* [ ] todo
* [x] done

A table:

| a | b |
| - | - |
`

createRoot(document.body).render(
  <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown>
)
Show equivalent JSX
<>
  <p>
    A paragraph with <em>emphasis</em> and <strong>strong importance</strong>.
  </p>
  <blockquote>
    <p>
      A block quote with <del>strikethrough</del> and a URL:{' '}
      <a href="https://reactjs.org">https://reactjs.org</a>.
    </p>
  </blockquote>
  <ul className="contains-task-list">
    <li>Lists</li>
    <li className="task-list-item">
      <input type="checkbox" disabled /> todo
    </li>
    <li className="task-list-item">
      <input type="checkbox" disabled checked /> done
    </li>
  </ul>
  <p>A table:</p>
  <table>
    <thead>
      <tr>
        <th>a</th>
        <th>b</th>
      </tr>
    </thead>
  </table>
</>

Use a plugin with options

This example shows how to use a plugin and give it options. To do that, use an array with the plugin at the first place, and the options second. remark-gfm has an option to allow only double tildes for strikethrough:

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'

const markdown = 'This ~is not~ strikethrough, but ~~this is~~!'

createRoot(document.body).render(
  <Markdown remarkPlugins={[[remarkGfm, {singleTilde: false}]]}>
    {markdown}
  </Markdown>
)
Show equivalent JSX
<p>
  This ~is not~ strikethrough, but <del>this is</del>!
</p>

Use custom components (syntax highlight)

This example shows how you can overwrite the normal handling of an element by passing a component. In this case, we apply syntax highlighting with the seriously super amazing react-syntax-highlighter by @conorhastings:

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism'

// Did you know you can use tildes instead of backticks for code in markdown? ✨
const markdown = `Here is some JavaScript code:

~~~js
console.log('It works!')
~~~
`

createRoot(document.body).render(
  <Markdown
    children={markdown}
    components={{
      code(props) {
        const {children, className, node, ...rest} = props
        const match = /language-(\w+)/.exec(className || '')
        return match ? (
          <SyntaxHighlighter
            {...rest}
            PreTag="div"
            children={String(children).replace(/\n$/, '')}
            language={match[1]}
            style={dark}
          />
        ) : (
          <code {...rest} className={className}>
            {children}
          </code>
        )
      }
    }}
  />
)
Show equivalent JSX
<>
  <p>Here is some JavaScript code:</p>
  <pre>
    <SyntaxHighlighter language="js" style={dark} PreTag="div" children="console.log('It works!')" />
  </pre>
</>

Use remark and rehype plugins (math)

This example shows how a syntax extension (through remark-math) is used to support math in markdown, and a transform plugin (rehype-katex) to render that math.

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'
import 'katex/dist/katex.min.css' // `rehype-katex` does not import the CSS for you

const markdown = `The lift coefficient ($C_L$) is a dimensionless coefficient.`

createRoot(document.body).render(
  <Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex]}>
    {markdown}
  </Markdown>
)
Show equivalent JSX
<p>
  The lift coefficient (
  <span className="katex">
    <span className="katex-mathml">
      <math xmlns="http://www.w3.org/1998/Math/MathML">{/* … */}</math>
    </span>
    <span className="katex-html" aria-hidden="true">
      {/* … */}
    </span>
  </span>
  ) is a dimensionless coefficient.
</p>

Plugins

We use unified, specifically remark for markdown and rehype for HTML, which are tools to transform content with plugins. Here are three good ways to find plugins:

Syntax

react-markdown follows CommonMark, which standardizes the differences between markdown implementations, by default. Some syntax extensions are supported through plugins.

We use micromark under the hood for our parsing. See its documentation for more information on markdown, CommonMark, and extensions.

Types

This package is fully typed with TypeScript. It exports the additional types AllowElement, ExtraProps, Components, Options, and UrlTransform.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, react-markdown@^9, compatible with Node.js 16.

They work in all modern browsers (essentially: everything not IE 11). You can use a bundler (such as esbuild, webpack, or Rollup) to use this package in your project, and use its options (or plugins) to add support for legacy browsers.

Architecture

                                                           react-markdown
         +----------------------------------------------------------------------------------------------------------------+
         |                                                                                                                |
         |  +----------+        +----------------+        +---------------+       +----------------+       +------------+ |
         |  |          |        |                |        |               |       |                |       |            | |
markdown-+->+  remark  +-mdast->+ remark plugins +-mdast->+ remark-rehype +-hast->+ rehype plugins +-hast->+ components +-+->react elements
         |  |          |        |                |        |               |       |                |       |            | |
         |  +----------+        +----------------+        +---------------+       +----------------+       +------------+ |
         |                                                                                                                |
         +----------------------------------------------------------------------------------------------------------------+

To understand what this project does, it’s important to first understand what unified does: please read through the unifiedjs/unified readme (the part until you hit the API section is required reading).

react-markdown is a unified pipeline — wrapped so that most folks don’t need to directly interact with unified. The processor goes through these steps:

  • parse markdown to mdast (markdown syntax tree)
  • transform through remark (markdown ecosystem)
  • transform mdast to hast (HTML syntax tree)
  • transform through rehype (HTML ecosystem)
  • render hast to React with components

Appendix A: HTML in markdown

react-markdown typically escapes HTML (or ignores it, with skipHtml) because it is dangerous and defeats the purpose of this library.

However, if you are in a trusted environment (you trust the markdown), and can spare the bundle size (±60kb minzipped), then you can use rehype-raw:

import React from 'react'
import {createRoot} from 'react-dom/client'
import Markdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'

const markdown = `<div class="note">

Some *emphasis* and <strong>strong</strong>!

</div>`

createRoot(document.body).render(
  <Markdown rehypePlugins={[rehypeRaw]}>{markdown}</Markdown>
)
Show equivalent JSX
<div className="note">
  <p>
    Some <em>emphasis</em> and <strong>strong</strong>!
  </p>
</div>

Note: HTML in markdown is still bound by how HTML works in CommonMark. Make sure to use blank lines around block-level HTML that again contains markdown!

Appendix B: Components

You can also change the things that come from markdown:

<Markdown
  components={{
    // Map `h1` (`# heading`) to use `h2`s.
    h1: 'h2',
    // Rewrite `em`s (`*like so*`) to `i` with a red foreground color.
    em(props) {
      const {node, ...rest} = props
      return <i style={{color: 'red'}} {...rest} />
    }
  }}
/>

The keys in components are HTML equivalents for the things you write with markdown (such as h1 for # heading). Normally, in markdown, those are: a, blockquote, br, code, em, h1, h2, h3, h4, h5, h6, hr, img, li, ol, p, pre, strong, and ul. With remark-gfm, you can also use del, input, table, tbody, td, th, thead, and tr. Other remark or rehype plugins that add support for new constructs will also work with react-markdown.

The props that are passed are what you probably would expect: an a (link) will get href (and title) props, and img (image) an src, alt and title, etc.

Every component will receive a node. This is the original Element from hast element being turned into a React element.

Appendix C: line endings in markdown (and JSX)

You might have trouble with how line endings work in markdown and JSX. We recommend the following, which solves all line ending problems:

// If you write actual markdown in your code, put your markdown in a variable;
// **do not indent markdown**:
const markdown = `
# This is perfect!
`

// Pass the value as an expresion as an only child:
const result = <Markdown>{markdown}</Markdown>

👆 That works. Read on for what doesn’t and why that is.

You might try to write markdown directly in your JSX and find that it does not work:

<Markdown>
  # Hi

  This is **not** a paragraph.
</Markdown>

The is because in JSX the whitespace (including line endings) is collapsed to a single space. So the above example is equivalent to:

<Markdown> # Hi This is **not** a paragraph. </Markdown>

Instead, to pass markdown to Markdown, you can use an expression: with a template literal:

<Markdown>{`
# Hi

This is a paragraph.
`}</Markdown>

Template literals have another potential problem, because they keep whitespace (including indentation) inside them. That means that the following does not turn into a heading:

<Markdown>{`
    # This is **not** a heading, it’s an indented code block
`}</Markdown>

Security

Use of react-markdown is secure by default. Overwriting urlTransform to something insecure will open you up to XSS vectors. Furthermore, the remarkPlugins, rehypePlugins, and components you use may be insecure.

To make sure the content is completely safe, even after what plugins do, use rehype-sanitize. It lets you define your own schema of what is and isn’t allowed.

Related

Contribute

See contributing.md in remarkjs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Espen Hovlandsdal

react-markdown's People

Contributors

alexanderwallin avatar christianmurphy avatar errorname avatar firsara avatar goto-bus-stop avatar jessepinho avatar lepozepo avatar liamsain avatar linusu avatar ljcooke avatar lucasassisrosa avatar marc2332 avatar marshallds avatar methuselah96 avatar mudrz avatar nvenegas avatar pajn avatar peng1999 avatar petrgazarov avatar philraj avatar rexxars avatar rikukissa avatar rwieruch avatar starpit avatar ted-piotrowski avatar thomaslindstrom avatar tiagoroldao avatar timwangdev avatar vinnl avatar wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-markdown's Issues

How to avoid <p> tag

Hello,
There is a p tag always get enclosed when i use the markdown component which always disturbs my page layout. Can you please tell how to avoid that.

image

How to get syntax highlight support?

Currently it shows a plain code block without any syntax highlighting. Could you please tell me how can I add a syntax highlighting support to it?

Nested lists dont render when parent is not plain text

This works just fine in the CommonMark reference tool.

* Follows the [CommonMark](http://commonmark.org/) spec
* Renders actual, "native" React DOM elements
* Allows you to escape or skip HTML (try toggling the checkboxes above)
* If you escape or skip the HTML, no `dangerouslySetInnerHTML` is used! Yay
  * more things
  * stuff and things
* another list

This does not render the nested list at all.

* Follows the [CommonMark](http://commonmark.org/) spec
* Renders actual, "native" React DOM elements
* Allows you to escape or skip HTML (try toggling the checkboxes above)
* If you escape or skip the HTML, no dangerouslySetInnerHTML is used! Yay
  * more things
  * stuff and things
* another list

This does. Any kind of markdown on the parent causes the nested list to be missed (bold, italics).

SemVer issues with 1.2.3

I wrote this here, but it is tied with react-commonmark-renderer too.

The update to the react-commonmark-renderer which updated the commonmark version itself included breaking changes which are somewhat incompatible with semver, which causes issues for those who have locked up the version of react-markdown. For example, my package was locked [email protected] due to #11. But as the react-markdown and react-commonmark-renderer are using the caret notation in package.json, it's possible for npm@3 to resolve the dependencies to both react-markdown and react-commonmark-renderer in a way that are incompatible, thus introducing breaking changes.

  1. npm install [email protected]
  2. Render a markdown file that would respond to Header in the old version (´Heading` in the new version)

Expected:

  • Should render a Header element

Actual:

  • Throws for unknown nodeType Header

The structure looks like this:

As the npm docs state

Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4

Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for versions 0.X >=0.1.0, and no updates for versions 0.0.X.

Many authors treat a 0.x version as if the x were the major "breaking-change" indicator.

Caret ranges are ideal when an author may make breaking changes between 0.2.4 and 0.3.0 releases, which is a common practice. However, it presumes that there will not be breaking changes between 0.2.4 and 0.2.5. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices.

As the requirement has changed from 0.22.0 to 0.24.0, npm picks up the newest version of 0.22.x instead -> 0.22.1.

Heading immediatly after `<br />` not rendered

Hi,

I just tried your component on some markdown we had in database and have an issue wit headings not rendering when placed immediately after an HTML <br /> tag.

example :

<br />
#### Test

Any idea why ?

Thanks !

Auto-linking URLs in text

I'm aware CommonMark doesn't specify this behavior, but would an option to enable auto-linking URLs found in text (like GitHub does) be considered?

Markdown adds a <p> tag when adding quote

Hi. We use react-markdown and then renderer prop to map the renderer types to our own components. We have quote component that renders a paragraf where the quote is and a cite tag.

but when i look a the browser markdown adds paragraf inside paragraf so they get nested

<blockquote class="block-quote__blockquote">
  <p class="block-quote__quote">
    <p class="running-text__RunningText">
    <!-- react-text: 578 -->“I have faced rejection so many times that I’ve lost track of how many times. Every time you’re asking someone to buy your product, you’re really asking them to embrace change…”<!-- /react-text -->
    </p>
  </p>
</blockquote>

can i prevent it from doing that?

Suggestion: allow 'plugins'

It would be awesome if we could add our own markdown.

For example, I like strikethrough, but it's not part of the CommonMark markdown spec, so I'd love to be able to add it. (Note: I don't want to allow HTML, so adding this would be a safer option)

~strike this~ ==> strike this

Standalone inline HTML tags rendered with extraneous DOM elements

It appears to only happen to inline HTML tags (<a>, <span>, etc.) when they are put in an isolated line.

Example

This:

<div>This is a normal line</div>

<a href="https://www.google.com">Google</a>

Gets compiled into this (For the sake of readability I've removed all the data-reactid):

<div>
    <div>This is a normal line</div>
</div>
<p>
    <span>
        <a href="https://www.google.com"></a>
    </span>
    <a href="https://www.google.com">
        <span>Google</span>
        <span></span>
    </a>
</p>

json-loader not specified as dependency

Im getting this error whenever I import react-markdown.

Module not found: Error: Cannot resolve module 'json-loader' in [REDACTED]/node_modules/entities/lib
resolve module json-loader in [REDACTED]/node_modules/entities/lib

I've commented the import, so I know it's that one, and I get no error. I installed "json-loader". Shouldn't json-loader or an equivalent package be specified as a dependency of react-markdown?

Code and blockquotes not displaying as expected

I could just be doing something wrong, but this is how the live demo text gets displayed in my app:

screen shot 2016-08-08 at 10 01 52 am

The code while code like is missing the box and the coloring
The blockquote is missing the left-hand bar.

looking at the elements, the code element is very different in my page than it is on the demo page:

Mine:
screen shot 2016-08-08 at 10 38 45 am

Demo:
screen shot 2016-08-08 at 10 38 31 am

My package.json reads:
"react": "^15.2.1",
"react-dom": "^15.1.0",
"react-markdown": "^2.4.2",

Any help would be greatly appreciated! Thanks!

Question regarding using links without allowing them

I want to render tags as link to my site #github => #github but I don't want to allow user to use the Link markdown syntax for anything else.
Currently I'm doing this which works but allows user to use the Link too

 (<ReactMarkdown source={prepare(this.props.text+' ')}
        softBreak="br"
        allowedTypes={['Text', 'Paragraph', 'Hardbreak', 'Emph', 'Strong', 'Item', 'List','Link']} />

function prepare(text){
  return U.tagify(text).reduce(function(acc, token){
      return acc + (U.isTag(token) ? makeLink(token) : token);
    }.bind(this))
}

function makeLink(token){
  return '['+token+'](/tag/'+token.substr(1)+')';
}

Is there any way to do that?

Webpack 2: You may need an appropriate loader to handle this file type

Looks like a bug 🐛

I'm using:

  • webpack v2.1.0-beta.27
  • json-loader v0.5.4
  • react-makdown v2.4.2

Following the instructions, I added to the json-loader to my webpack.config.babel.js:

{
    test: /\.json$/,
    loader: 'json-loader',
}

I'm trying to use package:

import React, { Component } from 'react'
import ReactMarkdown from 'react-markdown'

import info from './index.md'
import styles from './index.css'

class Content extends Component {
    render () {
        return (
            <content className={ styles.content }>
                <ReactMarkdown source={ info } />,
            </content>
        )
    }
}

export default Content

But have just the following output:

Hash: 4f07fbf9e1fdba4b7aea
Version: webpack 2.1.0-beta.27
Time: 25768ms
                               Asset     Size  Chunks             Chunk Names
0a7d43a8297f9411d0f57fc63bc3d4e0.jpg  21.2 kB          [emitted]  
504a3a6c4941f1d80e195f24622e8be1.png  34.3 kB          [emitted]  
     js/main.4f07fbf9e1fdba4b7aea.js   267 kB       0  [emitted]  main
   css/main.4f07fbf9e1fdba4b7aea.css   269 kB       0  [emitted]  main
  js/main.4f07fbf9e1fdba4b7aea.js.gz  91.1 kB          [emitted]  
                  assets/favicon.ico  1.15 kB          [emitted]  
         assets/apple-touch-icon.png  4.23 kB          [emitted]  
    + 236 hidden modules

ERROR in ./components/Content/index.md
Module parse failed: /home/azat/Dev/azat-io/components/Content/index.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| ##### lorem
| 
| Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
 @ ./components/Content/index.jsx 17:13-34
 @ ./components/Main/index.jsx
 @ ./components/App/index.jsx
 @ ./components/Root/index.jsx

ERROR in Error: Module parse failed: /home/azat/Dev/azat-io/components/Content/index.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
| ##### lorem
| 
| Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    at Object.e.__esModule.default (main:17:18954)
    at d (main:1:7158)
    at n (main:1:1264)
    at Object.e.__esModule.default (main:17:20584)
    at d (main:1:7158)
    at n (main:1:1264)
    at Object.i (main:17:27155)
    at d (main:1:7158)
    at n (main:1:1264)
    at Object.e.__esModule.default (main:17:18348)

Impor tMarkdown file

I import a .md file so that I can focus the markdown content in a single file.
But the console show: Module not found: ./components/MdContent.md

My code is something like this.

import React, { Component } from 'react';
import './../App.scss';
import MdContent from './components/MdContent.md';
var ReactMarkdown = require('react-markdown');
var input = {MdContent};

class YosgoMarkDown extends Component {

    render() {
        return(
            <div className="YosgoMarkDown">
                <ReactMarkdown source={input} />
            </div>
        );
    }
}
export default YosgoMarkDown;

I use create-react-app and my folder structure is like this
src
⎿ App.js
⎿ index.js
⎿ components
---⎿ YosgoMarkDown.js
---⎿ MdContent.md

Is there any wrong or some other advice to import a .md file?

Detect consecutive images

Hi,

Is there any way to detect consecutive images with react-markdown ?

Use case is, we write articles in markdown and want to provide a generic layout for images depending on the number of consecutive images.

For example:
1 image: full-width
2 images: side-by-side
3 images: 2 side-by-side and 1 full size underneath
4 images+: a gallery component

Thanks !

Errors with npm install and Running

Hi there. I have tried several times to get the development version working to no avail. Here is a screen shot of my terminal:
screen shot 2015-12-12 at 6 59 23 pm

I have done everything I can think of. The demo will not load at all. I have successfully installed via npm in my project and I can get the markdown rendered to the page, but nothing else. The documentation is unclear on how to get this to look like the demo page as well as how to start the demo. I tried the webpack command, npm start everything. I even created a directory and tried to run gulp to see if I could fix it, but no there also. Can you provide me an explanation as to what I am doing wrong?

How do I display a Table of Content (TOC)

First of all, great work everyone.

Is it possible to have a table of content next to the markdown document with react-markdown somehow?
I'd like to use it as a sidebar for a simple documentation page.

Support loading react from CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.min.js" charset="utf-8" crossorigin="anonymous"></script>
events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: module "react" not found from "/home/dodekeract/code/manta-config-engine-app/node_modules/react-markdown/src/react-markdown.js"
    at notFound (/home/dodekeract/code/manta-config-engine-app/node_modules/browserify/index.js:803:15)
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browserify/index.js:754:23
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/index.js:185:24
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:44:14
    at process (/home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:113:43)
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:122:21
    at load (/home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:54:43)
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:60:22
    at /home/dodekeract/code/manta-config-engine-app/node_modules/browser-resolve/node_modules/resolve/lib/async.js:16:47
    at FSReqWrap.oncomplete (fs.js:82:15)

React is not found, yes - because it's not installed via npm to save bandwidth. However, it will be available in the browser. Not sure how you can fix this, but it should be possible somehow.

How to protect against XSS?

For instance, this is currently failing for inputs like:

<img src="" onerror="alert()">
<a href="javascript:alert()">hey</a>

How to fix that? Is/how to make this component safe enough to be used?

Add new prop `sourceFile`

Usually markdown files are read from fs so I think having sourceFile will just make it easier to use it.

Something on similar lines:

require('fs')
.readFileSync(this.props.sourceFile, this.props.sourceFileEncoding || 'utf8', (err, file) => {
  this.setState({ source: file });
});

Support for <kbd>

Perhaps this can be fixed together with #16. Basically, our content includes <kbd>Enter</kbd> like text to render a keyboard hotkeys like Enter. There is a CSS defined for it. However, react-markdown renders it into:

<span><kbd></kbd></span><span>Enter</span>

Support for <sub>

Hi is there any plans to support superscript in this markdown parser? I tried using <sub>1</sub> but this tag gets converted to even if I specify skipHTML option.

Upgrade dependency of `commonmark`

Seems commonmark adds some breaking changes in version 0.23.0, and commonmark-react-renderer has been already updated.

Otherwise, a common error as Unknown node type "Header" would raise

Problem While Using Webpack 2

Webpack will successfully bundle my code that includes react-markdown, but during runtime I get this error:

Uncaught Error: Cannot find module "../maps/xml.json"

The module it's referring to is require'd in commonmark, but I suspect this is an issue many of you may have had/solved and I'm just blanking on a way around it. Any suggestions?
Thanks!

Here is my very basic webpack.config,

var config = {
	entry: './src/js/main.js',
	output: {
		filename: 'bundle.js',
		path: __dirname + '/src',
	},
	module: {
		rules: [
			{
				test: /\.jsx?$/,
				use: ['babel-loader'],
				include: __dirname + '/src/js',
			},
		]
	}
}

Limiting features available

Is it possible to limit the advanced markdown features.
I would like to have only below markdown

Emphasis

This text will be italic

This text will be bold

Lists

Unordered

  • Item 1
  • Item 2
    • Item 2a
    • Item 2b

Ordered

  1. Item 1
  2. Item 2
  3. Item 3
    • Item 3a
    • Item 3b

typings are not installed

Not sure why, but the react-markdown.d.ts file is not installed, it's not in my node_modules/react-markdown/ folder.

Support for unescaped newlines

We are migrating our web app from Backbone to React, and hoping to replace marked with react-markedown. The problem it, we need to convert single newlines to broken newlines (<br />), and I can't seem to find a way to do that in react-markdown.

This is the option we set in marked to enable this functionality: https://github.com/chjj/marked#breaks

We need this support for backwards compatibility in our app, as well as to follow the generally accepted Github style of markdown which is fairly well known to our users. From what I can tell, because react-markdown uses CommonMark, this is not something available as an option.

Any thoughts?

<br/> doesn't work

When typing 2 strings, and putting each on a new line using Enter. Instead of rendering a BR it will render each in a separate span (including empty span)

screen shot 2015-11-25 at 03 38 07

screen shot 2015-11-25 at 03 38 37

React 15.2.0 warning: Unknown prop `literal` on <p> tag

React 15.2.0 throws a warning if you try to assign custom props to DOM elements. Custom props should be assigned only to React components.

warning.js?8a56:44Warning: Unknown prop `literal` on <p> tag. Remove this prop from the element. For details, see https://fb.me/react-unknown-prop
    in p (created by ReactMarkdown)
    in div (created by ReactMarkdown)
    in ReactMarkdown (created by MY_APP_COMPONENT)

This warning appears with any source input.
I just had to fix the same thing in my library.

Render blows up if given slightly invalid markdown

Not sure what, if anything, I'm doing wrong here. This is all I'm specifying:

<Markdown escapeHtml={true} source={"Hello \n---\n**World**!"}/>

and I'm getting in the console:

Uncaught TypeError: Can't add property context, object is not extensible

If I add 2 \n between the --- and the rest, then it's not a problem.

Inline mathematics

Any tips on how I could modify react-markdown to parse additional nodes out? In particular, if I found an occurence of $$\int_0^\infty x^2 dx$$ in the text, I'd like to rely on react-katex to render like so:

 React.render(<BlockMath>\int_0^\infty x^2 dx</BlockMath>,
                document.getElementById('math'));

Can't get this working with Webpack

I'm trying to use this package in conjunction with developing components in React Storybook, but I'm getting the following errors:

ERROR in ./~/entities/maps/xml.json
Module parse failed: /Volumes/SuperData/GitHub/react-sketchpad/node_modules/entities/maps/xml.json Unexpected token (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:6)

I followed the instructions and installed json-loader, and below is my webpack.config.js:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    'webpack-dev-server/client?http://localhost:9000',
    'webpack/hot/only-dev-server',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['react-hot', 'babel'],
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
    ]
  }
};

Am I missing something?

Requiring "commonmark/dist/commonmark" breaks bundling processes

In 62df2b2 the Parser require was changed to:

``` diff`

  • var Parser = require('commonmark/dist/commonmark').Parser;

This fails at least on Node v4-5, npm@3 and `Browserify` with error

Error: Cannot find module './common' from 'D:\Projects\crf\node_modules\react-markdown\node_modules\commonmark\dist'


There's also an comment from @just-paja in the commit with same happening with `Webpack`

> I like your project, but this breaks webpack for me with a This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results error.

transformLinkUri not working with images link

Hello, I've testet the component and wanted to change link of images in markdown like

![insert images](../images/myImage.png)

changing the '../images/myImage.png' to 'http://someserverofMine.com/images/myImage.png' but it's not passing through my function if i use '!['

Without the '!' it's passing through my function

[insert images](../images/myImage.png)

bu then it's a link, not an image that is displayed but a link.

for info here is the usage of the component

<ReactMarkdown transformLinkUri={this.myTransformLinkUri} source={this.state.content}/>

do you have a workarround ?

Bug in title display

#title
# title

title

title

why the space between '#' and title must be added?

Text defaulting to bold

I'm having a problem rendering some Markdown
What happens is that all the text is rendered as bold

For example, for this text

**This should be bold**

This shouldn't be bold

I'm seeing this render
captura de pantalla 2016-09-23 a las 21 11 20

Any ideas of what might be happening?

This is the code where I render the markdown

<Markdown source={body}/>

body is a string

<img/> element can't trigger the transformImageUri function

Hello.
I have some <img/> tags in markdown, and I want to handle the src attrs in these elements. So I use the transformImageUri function, hoping to get original uri as input and return new uri.
However, I found that if the element is already <img/> in the markdown, it can't trigger the transformImageUri function. Any solution to deal with this condition? Thx

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.