Skip to content
Advertisement

gatsby-image-background using v3 gatsby-image

I am trying to make gatsby-background-image work with v3 of gatsby-plugin-image. I have followed documentation and found I should be using gbimage-bridge.

For some reason it doesn’t seem to work. My query works fine when testing in ide. I have tried to change my query and consts in all sorts of ways but can’t seem to make it work.

Right now it just outputs the text Test but no background is being displayed.

My code:

import { graphql, useStaticQuery } from "gatsby"
import { getImage } from "gatsby-plugin-image"
import { BgImage } from "gbimage-bridge"

const GbiBridged = () => {
  const { backgroundImage123 } = useStaticQuery(graphql`
    query {
      backgroundImage123: allWpPage {
        nodes {
          ACFforside {
            heroimg {
              localFile {
                childImageSharp {
                  gatsbyImageData(
                    width: 2000
                    quality: 50
                    placeholder: BLURRED
                    formats: [AUTO, WEBP, AVIF]
                  )
                }
              }
            }
          }
        }
      }
    }
  `)

  const pluginImage = getImage(backgroundImage123)

  return (
        <BgImage image={pluginImage}>Test</BgImage>
  )
}

export default GbiBridged

Advertisement

Answer

I think your snippet should look like:

import React from 'react'
import { graphql, useStaticQuery } from 'gatsby'
import { getImage, GatsbyImage } from "gatsby-plugin-image"

import { convertToBgImage } from "gbimage-bridge"
import BackgroundImage from 'gatsby-background-image'

const GbiBridged = () => {
  const { backgroundImage123 } = useStaticQuery(
    graphql`
      query {
        backgroundImage123: allWpPage {
          nodes {
           ACFforside {
             heroimg {
               localFile {
                 childImageSharp {
                   gatsbyImageData(
                     width: 2000
                     quality: 50
                     placeholder: BLURRED
                     formats: [AUTO, WEBP, AVIF]
                   )
                 }
               }
             }
           }
         }
       }
     }
    `
  )
  const image = getImage(backgroundImage123.nodes[0].ACFforside.heroimg.localFile)

  // Use like this:
  const bgImage = convertToBgImage(image)

  return (
    <BackgroundImage
      Tag="section"
      // Spread bgImage into BackgroundImage:
      {...bgImage}
      preserveStackingContext
    >
      <div style={{minHeight: 1000, minWidth: 1000}}>
        <GatsbyImage image={image} alt={"testimage"}/>
      </div>
    </BackgroundImage>
  )
}
export default GbiBridged

I’m assuming that your query is fetching the right nodes, otherwise, test it in the localhost:8000/___graphql playground

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement