Gatsby StaticImage src value not accepted via dot notation

Viewed 307

I understand that you cannot pass the source of an image to the StaticImage component as the result of a function. However, can anyone explain to me the difference between these two examples.

import React from 'react'
import { StaticImage } from 'gatsby-plugin-image' // to take image data and render it

export default function Example() {
  const imageSrc = '../images/jonathan-adams.jpg'
  const data = {
    imageSrc: '../images/jonathan-adams.jpg',
  }
  return (
    <div>
      <StaticImage src={imageSrc} alt="alt text" /> {/* works */}
      <StaticImage src={data.imageSrc} alt="alt text" /> {/* doesn't work */}
    </div>
  )
}

One is a direct variable reference, and the latter is referencing the same value, but through dot notation. Is dot notation a function?

1 Answers

Is dot notation a function?

It's not a function but it's not a constant value (at least it can't be treated as constant in the scope of the StaticImage component) hence it can't be statically analyzed, since in the end, what it's constant is data, not its nested properties. That's why imageSrc works but data isn't.

Restrictions on using StaticImage

The images are loaded and processed at build time, so there are restrictions on how you pass props to the component. The values need to be statically-analyzed at build time, which means you can’t pass them as props from outside the component, or use the results of function calls, for example. You can either use static values, or variables within the component’s local scope.

Source: https://www.gatsbyjs.com/docs/reference/built-in-components/gatsby-plugin-image/#restrictions-on-using-staticimage

That said, you may want to use imageSrc approach or considering using GatsbyImage which accepts dynamic values (it will need a refactor and GraphQL-based approach).

Related