Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda