Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!