Unable to add images to mdx file in Gatsby

Viewed 1908

I am trying to import an image into an mdx file by doing this: ![alt](image.jpg). My mdx file and image are both stored in the directory src, posts, post-1. However, the image does not display. I've tried numerous file paths with no luck.

The only way I've been able to get images to display is by using src e.g. ![alt](/static/47d93fd9bdeaaf54a7b60d14c66abe5d/48e00/icon.jpg)

Below is part of my gatsby.config

plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `pages`,
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "images",
        path: `${__dirname}/src/images/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/posts/`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `post-featured`,
        path: `${__dirname}/src/post-featured/`,
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        root: __dirname,
        extensions: [".md", ".mdx"],
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 800,
              quality: 70,
            },
          },
        ],
      },
    },
3 Answers

I have worked my way around this issue by adding an images array to my blog post mdx frontmatter e.g. images: [formby-golf-club.jpg, myFirstTweet.PNG].

Then in my post template I grab the publicURL of the images in the array via graphQL, and pass them into MDXRenderer, like so: <MDXRenderer images={data.mdx.frontmatter.images}>.

I can then access the images array in my mdx file like this: <img src={props.images[0].publicURL} style={{ width: "100%" }} />

I had the same problem after reading official how-to guide and adding gatsby-remark-image as a single entry in plugins array. Keeping it only inside gatsby-plugin-mdx solved the issue for me.

Related