1

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

11 Comments

You don't need const _this = this when using arrow functions, this is lexically bound.
Thanks, that makes it even more simple.
Yes, I'm using webpack. But there is a need to render any `*.md* file, so I could not require specific one.
Then the GET request is probably your best option.
A code example is right there in my answer. I'm doing a GET request to a remote .md file and render it. Click on "Run code snippet" to see what the code is doing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.