John Doe John Doe - 9 days ago 5
Markdown Question

React render *.md via custom component

Its easy to render markdown data via

react-markdown
module. But I cant implement render all
*.md
files via custom
MarkdownPage
component:

<Route path="*.md" component={MarkdownPage} />


but route didn't work and
*.md
-files open in browser as-is.

I'm expecting that this file will be provided as a data to component via
props
, to do something like:

render() {
return (
<h1>Pretty markdown</h1>
<Page>
<ReactMarkdown source={this.props} />
</Page>
);
}


How could I achieve this?

Answer

One approach would be to use a GET request to either a .md file or a JSON that includes the markdown as a string. Here's an example of that:

class ReactMarkdown extends React.Component {
  constructor() {
    super();
    this.state = { html: '' };
  }

  componentDidMount() {
    fetch(this.props.md)
      .then(response => response.text())
      .then(markdown => this.setState({ html: marked(markdown) }));
  }

  render() {
    return (
      <div dangerouslySetInnerHTML={{ __html: this.state.html }}></div>
    );
  }
}

ReactDOM.render(<ReactMarkdown md="https://cdn.rawgit.com/fabe/react-portfolio/master/README.md"/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

With React Router:

<Route path="/markdown/:file" component={MarkdownPage} />
// Example route: localhost:3000/markdown/x.md

Then inside your component:

fetch('/' + this.props.params.file)