Download dependency.

yarn add react-markdown

yarn add remark-gfm   
yarn add rehype-raw   
yarn add react-syntax-highlighter   
yarn add github-markdown-css 

Use fetch to fetch the contents of a Markdown file and render it using react-markdown.

import React from 'react';
import ReactMarkdown from 'react-markdown';
 
const App=({url})=>{
 
  const [mdContent, setMdContent] = useState('')
 
  useEffect(() => {
      fetch(url)
             .then(res => res.text())
             .then(text => setMdContent(text));
      }
    }, []);
 
    return(
        <ReactMarkdown
         className='markdown-body'
         children={mdContent}
         />
    )
}
 
export default App 

Styling
At this point it is possible to read markdown files, but there is a single style, with tables, headings, code blocks and other styles not shown, and there is no navigation bar as in editors such as Typora. The next step is to beautify the content. This is still done through plugins.

import React from 'react';
import ReactMarkdown from 'react-markdown';
// Syntax extensions for underlining, tables, task lists and direct URLs
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw'// Parsing tags, supporting html syntax
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' // Code highlight
//Highlighted themes, and many others to choose
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';
// Styles such as code backgrounds and table lines
import 'github-markdown-css';
 
 
const App=({url})=>{
 
  const [mdContent, setMdContent] = useState('')
 
  useEffect(() => {
      fetch(url)
             .then(res => res.text())
             .then(text => setMdContent(text));
      }
    }, []);
 
    return(
        <ReactMarkdown
         className='markdown-body'
         children={mdContent}
         remarkPlugins={[remarkGfm, { singleTilde: false }]}
         rehypePlugins={[rehypeRaw]}
         components={{
             code({ node, inline, className, children, ...props }) {
                 const match = /language-(\w+)/.exec(className || '')
                 return !inline && match ? (
                     <SyntaxHighlighter
                         children={String(children).replace(/\n$/, '')}
                         style={tomorrow}
                         language={match[1]}
                         PreTag="div"
                         {...props}
                     />
                 ) : (
                     <code className={className} {...props}>
                         {children}
                     </code>
                 )
             }
         }}
         />
    )
}
 
export default App 

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *