Primero lo importo así:
import marked from "marked"; Luego busco mi archivo *.md dentro del evento componentDidMount de React y lo almaceno en el estado de mi componente usando marked(text) (donde el text es la respuesta):
componentDidMount() { const readmePath = require("./Readme.md"); fetch(readmePath) .then(response => { return response.text() }) .then(text => { this.setState({ markdown: marked(text) }) }) } ... y finalmente lo presento en la página usando el atributo dangerouslySetInnerHTML SetInnerHTML:
render() { const { markdown } = this.state; return ( <section> <article dangerouslySetInnerHTML={{__html: markdown}}></article> </section> ) }Un ejemplo de trabajo completo con 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 TermsDebe usar react-markdown en lugar de la respuesta aceptada , esta solución no usa dangerouslySetInnerHTML .
Aplicación.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;Aplicación.md
# React & Markdown App * Benefits of using React... but... * Write layout in Markdown!