Gatsby - Markdown

> (World Wide) Web - (W3|WWW)

1 - About

How to show markdown page in React Framework - Gatsby

Markdown page are a gatsby dynamic page creation process

3 - Steps

3.1 - Add the transformer

yarn add gatsby-transformer-remark

3.2 - Create a markdown document

A markdown document in the pages directory with a Markup - front matter.

src/pages/hello-world.md
---
title: "Hello World"
date: "2017-08-10"
---
 
# A big hello World
 
## About
 
A [Link to another markdown page](/two/) does not has the extension file.
Advertising

3.3 - Create a template

Markdown data are exposed via the graphiQl server. You need to query them and to use them in template. This template is also define in the configuration step below (ie in gatsby-node.js file)

/src/templates/markdown.js
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
 
export default ({ data }) => {
  const post = data.markdownRemark
  return (
    <Layout>
      <div>
        <h1>{post.frontmatter.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.html }} />
      </div>
    </Layout>
  )
}
 
export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        title
      }
    }
  }
`

3.4 - Expose the markdown as data and creates the pages

gatsby-node.js
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
 
exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` })
    createNodeField({
      node,
      name: `slug`,
      value: slug,
    })
  }
}
 
exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `).then(result => {
    result.data.allMarkdownRemark.edges.forEach(({ node }) => {
      createPage({
        path: node.fields.slug,
        component: path.resolve(`./src/templates/markdown.js`),
        context: {
          // Data passed to context is available
          // in page queries as GraphQL variables.
          slug: node.fields.slug,
        },
      })
    })
  })
}

3.5 - Result

  • Restart the development server
gatsby development

If you hit a 404 (http://localhost:800o/sdf), you should be able to see the page in the list.

4 - Documentation / Reference

web/gatsby_markdown.txt · Last modified: 2019/06/21 14:42 by gerardnico