GatsbyJS - Relative img tag src that point to specific directory/source

Viewed 112

I'm trying to create a static site with GatsbyJS and I need to resolve the img tags so that relative URLs point to a certain directory, while absolute ones (which start with http(s):// work normally).
I've tried making a proper component, but since it's not a page, Graphql won't run:

import React from "react"
import { graphql } from "gatsby"

// Component constants
const absUrlRex = new RegExp(/^https?:\/\//, "i")

// Component
const CustomImg = ({ src, data, ...props }) => {
    let imgSrc = src
    if (!absUrlRex.test(src)) {
        if (null !== data.file) {
            imgSrc = data.file.publicURL
        } else {
            console.log(`Image "${src}" NOT found!`)
        }
    }

    return <img src={imgSrc} {...props} />
}

export default React.memo(
    CustomImg,
    (prev, next) => next.src === prev.src
)

export const query = graphql`
    query($src: String!) {
        file (
            sourceInstanceName: {eq: "images"},
            relativePath: {eq: $src}
        ) {
            publicURL
        }
    }
`

I've already tried StaticImage of "gatsby-plugin-image", but the src parameter is not a static string, so it doesn't work.

1 Answers

You are running a page query in a component. That will never work because page queries only works in top-level components (pages), hence the name.

Because you are using a dynamic GraphQL filter parameter ($src: String!) using a static query is not an option (they don't accept dynamic parameters, hence the name) so your only chance is to move the query into a page component and drill down the file into the component as a prop.

Related