How do I load a markdown file into a react component?
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!
markdown-to-jsx provides very efficeint functionality to interact with markdown in React component.
It allows replacing/overriding of any HTML element with your Custom Component for markdown, here is the doc.
import React, { Component } from 'react'
import Markdown from 'markdown-to-jsx';
import README from './README.md'
class PageComponent extends Component {
constructor(props) {
super(props)
this.state = { md: "" }
}
componentWillMount() {
fetch(README)
.then((res) => res.text())
.then((md) => {
this.setState({ md })
})
}
render() {
let { md } = this.state
return (
<div className="post">
<Markdown children={md}/>
</div>
)
}
}
export default PageComponent
Edit 2nd Aug'21
Functional Component
const PageComponent = ()=> {
let [ content, setContent] = useState({md: ""});
useEffect(()=> {
fetch(README)
.then((res) => res.text())
.then((md) => {
setContent({ md })
})
}, [])
return (
<div className="post">
<Markdown children={content.md}/>
</div>
)
}
I use marked (GitHub).
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>
)
}