I first import it like this:
import marked from "marked";
I then fetch my *.md file within React's componentDidMount event and store it in my component's state using marked(text) (where text is the response):
componentDidMount() {
const readmePath = require("./Readme.md");
fetch(readmePath)
.then(response => {
return response.text()
})
.then(text => {
this.setState({
markdown: marked(text)
})
})
}
...and finally I render it on the page using the dangerouslySetInnerHTML attribute:
render() {
const { markdown } = this.state;
return (
<section>
<article dangerouslySetInnerHTML={{__html: markdown}}></article>
</section>
)
}
A full working example with react-markdown:
import React, { Component } from 'react'
import ReactMarkdown from 'react-markdown'
import termsFrPath from './Terms.fr.md'
class Terms extends Component {
constructor(props) {
super(props)
this.state = { terms: null }
}
componentWillMount() {
fetch(termsFrPath).then((response) => response.text()).then((text) => {
this.setState({ terms: text })
})
}
render() {
return (
<div className="content">
<ReactMarkdown source={this.state.terms} />
</div>
)
}
}
export default Terms
You should use react-markdown instead of the accepted answer, this solution doesn't use dangerouslySetInnerHTML.
App.js
import React, { Component } from 'react';
import AppMarkdown from './App.md';
import ReactMarkdown from 'react-markdown';
class App extends Component {
constructor() {
super();
this.state = { markdown: '' };
}
componentWillMount() {
// Get the contents from the Markdown file and put them in the React state, so we can reference it in render() below.
fetch(AppMarkdown).then(res => res.text()).then(text => this.setState({ markdown: text }));
}
render() {
const { markdown } = this.state;
return <ReactMarkdown source={markdown} />;
}
}
export default App;
App.md
# React & Markdown App
* Benefits of using React... but...
* Write layout in Markdown!