简体   繁体   中英

Working with images local files in Gatsby.js

I am trying to render a headshot for each artist displayed on the page. The artist data comes from a Json file, and the images are located in images/artists/headshots. I am using the regular img tag, but for some reason nothing is displaying on the page. Any help any one can give would be greatly appreciated.

import React from 'react'
import PropTypes from 'prop-types'
import { StaticImage } from 'gatsby-plugin-image'

import { useStyles } from './styles'

const ArtistsPage = ({ data }) => {
  const classes = useStyles()

  return (
    <section>
      <article className={classes.artistsBackground}>
        <div className={classes.heroLayoutContainer}>
          <h3 className={classes.title}>MEET THE ARTISTS</h3>

          <StaticImage
            className={classes.heroImage}
         src='../../images/artists/hero-images/hero-image-artists.jpg'
            alt='hero-image-artists'
            placeholder='blurred'
          />
        </div>
      </article>
      <article className={classes.artistsContainer}>
        <div className={classes.flexContainer}>
          {data.allArtistsJson.edges
            .map(({ node }, idx) => {
              const artist = `${node.firstName}+${node.lastName}`
                .split('+')
                .join(' ')

              return (
                <div className={classes.flexItem} key={idx}>
                  <div>
                    <img
                      src={`../../images/artists/headshots/${artist} Headshot.jpg`}
                      alt='artist-headshot'
                    />
                  </div>
                  <div className={classes.artistCardName}>
                    {`${node.firstName} ${node.lastName}`.toUpperCase()}
                  </div>
                  <div className={classes.artistCardText}>{node.city}</div>
                  <div className={classes.artistCardText}>
                    {node.currentTeam}
                  </div>
                </div>
              )
            })}
        </div>
      </article>
    </section>
  )
}

export default ArtistsPage

My image files are set up as: FirstName LastName Headshots.jpg

I think your issue may comes from the white spaces in the naming. Your code looks good at first sight so try renaming your images with underscore or in camelCase:

   <img
      src={`../../images/artists/headshots/${artist}_Headshot.jpg`}
      alt='artist-headshot'
    />

After much research and the nice people on Gatsby discord I found the answer to be… in a scenario like this I needed to add require().default.
Ex: <img src={require( ../../images/artists/headshots/${artist} Headshot.jpg ).default} alt='artist-headshot' />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM