In Gatsbyjs, how to render markdown images when markdown is coming from a yaml object property?

259 Views Asked by At

I am working with a gatsbyjs app, where I have some .yml files that have following format:

enter image description here

My goal is to render value of markdownContent field as HTML. For that purpose, I first read contents of these .yml files using 'gatsby-transformer-yaml' plugin and then I use remark and remark-html to convert the value of markdownContent field to html.

The html renders just fine, however I couldn't get the image (linked as part of markdownContent field) to render (all image requests return in 404)

Is it even possible this way? If not, how can I get my markdown images to render in HTML when the markdown is not coming from gatsby-markdown-remark?

1

There are 1 best solutions below

0
On

You can use gatsby-transformer-yaml-full which will create a queryable GraphQL node from a YAML input.

Once installed it (by npm install gatsby-transformer-yaml-full or its yarn equivalent):

// gatsby-config.js

module.exports = {
  plugins: [
    'gatsby-transformer-yaml-full',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: './content', // Path to your .yaml (or .yml) files
      },
    },
  ],
}

This will allow the plugin to create GraphQL nodes, exposed as allCollectionYaml. For example:

{
  allCollectionYaml {
    edges {
      node {
        character
        number
      }
    }
  }
}

Then in your page/template you just need to access the GraphQL data (stored inside data object in the page props) and use dangerouslySetInnerHTML to render it:

function MyComponent() {
  return <div dangerouslySetInnerHTML={{ __html: props.data.allCollectionYaml.edges.node[0].character}} />;
}

Alternatively, you can use a safer option like markdown-to-jsx.