How to include Markdown pages in React

Date 13 juillet 2016 Catégories Developpement par VulgaireDev

The main project i am currently working on is a playground wich illustrate the possibilities of a REST API, which aim is to normalize and unify the cloud management (more infos on a next article, i guess?).

To do so, I use React. One of the features of this playground is that, like in a Documentation, you have some Readings. You click on a Menu, then you can read on a specific location of the page. In a previous project, I did it with HTML files that I included, but we wan do way better. We can use Markdown.

Before starting, I assume that you already know the basics of React, webpack and npm.

What is Markdown ?

Well, it is a simple way of formating text. More simple than HTML and CSS, simpler than Latex for example.

Mardown is used on Github, on many blogs, and often in documentation nowadays. Here is a simple example of how Mardown code:

# Mardown title

Here is some text

* This is an element of bullet list
* this is another

This is a link [myBeautifulLink](www.google.com)

## Mardown subtitle

<blockquote>
    This is a bloquote
</blockquote>

## How about some code?

```js
var React = require('react');

var i = 25;
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

And the result :

You can find a markdown cheatsheet here https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

A cool thing with Markdown is its simplicity, so when you have a markdown system, you can edit easily, without wasting time. Moreover, the result is beautiful, normalized, and people can contribute easily to the modification of the markdown file : it is well-known among developers, and it is quite user friendly.

When we have a system like the one we are going to make, we can do interesing things, for instance take the documentation.md (or the wiki) of a Github project, and use it directly on another website via a call to the GitHub API ! This way, there is a unique source of truth for the documentation.

How to use it with React ?

First, we will use react-markdown https://github.com/rexxars/react-markdown

npm install --save react-markdown

Then, you need to install a JSON loader :

npm install --save json-loader

Then add the loader to webpack:

{
    module: {
        loaders: [{
            test: /\.json$/,
            loader: 'json'
        }]
    }
}

Then, important part, you must specify that you want to read the mardown file as a raw string, to give to ReactMarkdown, or else webpack will have a problem. To do so, you need to install webpack-raw-loader:

npm install --save raw-loader

Once this is done, you can choose the part of your application where you want to display the Markdown  (I have a specific component for tha):

import React from 'react';
import ReactMarkdown from 'react-markdown';
import CodeBlock from '../code-block.js';

{/*We use the raw loader here*/}
var mardownFile = require('raw!./readings/GettingStarted.md');

export default class Reading extends React.Component{

  render() {
    return (
      <div className="ui reading segmentpadding">
        <ReactMarkdown source={mardownFile} renderers={Object.assign({}, ReactMarkdown.renderers, {
                            CodeBlock: CodeBlock })}/>
      </div>
    );
  }
}

So we give to the ReactMardown component a source, which is the markdown file we want to display, and "renderers". We need this to specify the highlighting of the code we put in the markdown. Indeed, if you don't do this, instead of having this :

You will have this :

To activate highlight, just copy this file (that i modified a little from here) :

var React = require('react');
var hljs = window.hljs;

export default class CodeBlock extends React.Component{
    componentDidMount = () => {
        this.highlightCode();
    }

    componentDidUpdate = () => {
        this.highlightCode();
    }

    highlightCode = () => {
        hljs.highlightBlock(this.refs.code);
    }

    render() {
        return (
            <pre>
              <code className={this.props.language} ref="code">
                {this.props.literal}
              </code>
            </pre>
        );
    }
};

Finally, include the highlight.js into you index.html :

<head>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/styles/github.min.css" />
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/highlight.min.js"></script>
</head>

 

Here you are, you can include markdown files into React !

I keeped just the essential code, for the sake of simplicity, but you can find a demo project here :

https://github.com/Romathonat/markdown-react-demo

 

Some links :

https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

https://github.com/rexxars/react-markdown

Commentaires

blog comments powered by Disqus