fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 5 MIN READ

Markdown Coolness

Using Markdown in React applications

From the original Fervor library. Examples may use older package versions.

Creating a web application that fetches a Markdown file and displays it using React Markdown can be a handy skill, especially for projects like blogs, documentation sites, or personal portfolios where content management is essential. Here’s a step-by-step tutorial on how to accomplish this using React.

Prerequisites

Before starting, make sure you have the following installed:

  • Node.js and npm (Node Package Manager)
  • A basic understanding of React

Step 1: Set Up Your React Project

If you don’t already have a React application set up, you can create one quickly using Create React App by running the following command:

npx create-react-app markdown-display
cd markdown-display

Step 2: Install Dependencies

You will need react-markdown to parse and display Markdown content. Install it and a fetch library (if you are not using the native fetch API) using npm:

npm install react-markdown

Step 3: Create a Markdown File

For this tutorial, create a simple Markdown file named example.md in the public folder of your project. Here’s an example Markdown content:

# Welcome to My Markdown Page

This is a simple markdown file to demonstrate loading Markdown in a React app.

## Here's a Subheading

- This
- Is
- A
- List

Enjoy!

Step 4: Fetch the Markdown File

Create a new component that will fetch and display the Markdown content. Let’s call this component MarkdownViewer.js. Here’s how you can set it up:

import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';

function MarkdownViewer() {
  const [markdown, setMarkdown] = useState('');

  useEffect(() => {
    fetch('/example.md')
      .then(response => response.text())
      .then(text => setMarkdown(text))
      .catch(error => console.error('Error loading the Markdown file: ', error));
  }, []);

  return (
    <div className="markdown-body">
      <ReactMarkdown children={markdown} />
    </div>
  );
}

export default MarkdownViewer;

In this component:

  • We use the useState hook to maintain the Markdown content.
  • The useEffect hook handles fetching the Markdown file when the component mounts.
  • fetch() is used to get the file from the public directory.
  • ReactMarkdown component from react-markdown is used to parse and render the Markdown content.

Step 5: Include the Viewer in Your App

Now, include the MarkdownViewer component in your main App.js file so it can be rendered:

import React from 'react';
import './App.css';
import MarkdownViewer from './MarkdownViewer';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>React Markdown Example</h1>
      </header>
      <MarkdownViewer />
    </div>
  );
}

export default App;

Step 6: Styling (Optional)

If you want to improve the appearance of the Markdown output, you can add some CSS in your App.css or another stylesheet. GitHub’s Markdown styles are quite popular and can be included easily.

Step 7: Run Your Application

Now, everything is set up! Run your application:

npm start

This will start the development server, and you should be able to see your Markdown file rendered in the browser.

Conclusion

You now have a simple React application that can fetch and display Markdown files dynamically. This setup can be expanded with more complex Markdown documents, styled components, or even integrating with a backend to fetch multiple files dynamically.

Bonus making codeblocks look cool

To integrate code block styling with syntax highlighting directly into the Markdown fetching component we discussed earlier, we’ll continue using react-markdown and react-syntax-highlighter. Here’s how you can update the MarkdownViewer component to fetch a Markdown file, render it, and style the code blocks within it.

Step 1: Update Your Project Setup

If you’re following from a previous setup, make sure you have the project ready. If not, you can quickly set up a new React project using Create React App, and navigate into your project directory:

npx create-react-app markdown-with-code-style
cd markdown-with-code-style

Step 2: Install Required Libraries

You’ll need to install react-markdown for rendering Markdown and react-syntax-highlighter for the code syntax highlighting. Run the following command to install these:

npm install react-markdown react-syntax-highlighter

Step 3: Update the Markdown Viewer Component

Modify the MarkdownViewer.js component to include syntax highlighting. Here’s how you can do it:

import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'; // or any other style you prefer

const MarkdownViewer = () => {
    const [markdown, setMarkdown] = useState('');

    useEffect(() => {
        fetch('/example.md') // Ensure you have example.md in your public folder
            .then(response => response.text())
            .then(text => setMarkdown(text))
            .catch(error => console.error('Error loading the Markdown file:', error));
    }, []);

    return (
        <div>
            <ReactMarkdown
                children={markdown}
                components={{
                    code({node, inline, className, children, ...props}) {
                        const match = /language-(\w+)/.exec(className || '')
                        return !inline && match ? (
                            <SyntaxHighlighter
                                style={vscDarkPlus}
                                language={match[1]}
                                PreTag="div"
                                {...props}
                            >
                                {String(children).replace(/\n$/, '')}
                            </SyntaxHighlighter>
                        ) : (
                            <code className={className} {...props}>
                                {children}
                            </code>
                        )
                    }
                }}
            />
        </div>
    );
}

export default MarkdownViewer;

What This Code Does:

  • Fetches the Markdown: It loads a Markdown file from your public directory.
  • Components Prop: This prop in ReactMarkdown is used to customize the rendering of markdown components. Here, it’s used to render code blocks using SyntaxHighlighter.
  • Syntax Highlighting: The code component checks if the code block is inline or block type. If it’s a block (not inline and has a language class), it renders it using SyntaxHighlighter.
  • Style Import: vscDarkPlus is one of the many styles/themes available for code highlighting, chosen to emulate the popular Visual Studio Code dark theme.

Step 4: Use the Component in Your App

Include this viewer component in your main application (App.js):

import React from 'react';
import './App.css';
import MarkdownViewer from './MarkdownViewer';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Markdown with Code Styling</h1>
      </header>
      <MarkdownViewer />
    </div>
  );
}

export default App;

Step 5: Run Your Application

Launch your application to see everything in action:

npm start

This command starts the development server, and you should be able to see your Markdown file rendered with syntax-highlighted code blocks in the browser.

Conclusion

By updating the MarkdownViewer component to include ReactMarkdown and ReactSyntaxHighlighter, you’ve effectively created a component that can fetch, display, and beautifully style Markdown content along with code snippets. This setup is excellent for any technical content, providing both functionality and visual appeal.

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY