How to use gatsby background image plugin

2.2k Views Asked by At

I'm new to gatsby and i'm trying to use gatsby background image plugin but it does not work, the image wont show on screen.

Here's my code :

import * as React from "react"
import { graphql, useStaticQuery } from 'gatsby'
import { createGlobalStyle } from "styled-components"
import BackgroundImage from 'gatsby-background-image'


const GlobalStyle = createGlobalStyle`
body{
    background-color: #270A63;
    margin : 0px;
   display:flex;
   
    
}`


const Layout = (props, { children }) => {

  const data = useStaticQuery(
    graphql`
      query {
        bgImage : file(relativePath: {eq: "background.png"}) {
          childImageSharp {
            gatsbyImageData(quality: 90)
          }
        }
      }
    `
  )

  const imageData = data.bgImage.childImageSharp.gatsbyImageData;

  return (
    <React.Fragment>
      <GlobalStyle />
      <BackgroundImage

        Tag="section"
        image={imageData}
        
      >
      </BackgroundImage>

    </React.Fragment>

  )
 
}

export default Layout

Layout is a custom component that I'm using in index page. I used console.log to check imageData and it is an object that looks like this :

{bgImage:
childImageSharp:
gatsbyImageData:
backgroundColor: "#680818"
height: 1117
images:
fallback: {src: '/static/32d467ee3060062ab794e34f2002c807/f89cf/background.png', srcSet: '/static/32d467ee3060062ab794e34f2002c807/5829e/bac…60062ab794e34f2002c807/f89cf/background.png 1010w', sizes: '(min-width: 1010px) 1010px, 100vw'}
sources: [{…}]
[[Prototype]]: Object
layout: "constrained"
width: 1010}

I don't understand why it does not work.

Thank you for your help !

2

There are 2 best solutions below

0
On BEST ANSWER

As per your GraphQL, you are using a Gatsby version greater or equal than 3. I think your snippet should look like something 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 { bgImage }= useStaticQuery(
    graphql`
      query {
        bgImage : file(relativePath: {eq: "background.png"}) {
          childImageSharp {
            gatsbyImageData(quality: 90)
          }
        }
      }
    `
  )
  const image = getImage(bgImage)
  const backgroundImage= convertToBgImage(image)

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

Modified from: https://www.gatsbyjs.com/plugins/gatsby-background-image/#gatsby-34--gatsby-plugin-image applying your code

Gatsby changed the image plugin from gatsby-image (Gatsby 1 and 2) to gatsby-plugin-image (version 3 onwards). Among other things, it has changed the internal GraphQL nodes of the image data, hence the workaround of using gatsby-background-image has also changed accordingly. In your case, you are using the deprecated version of gatsby-image so your code is not able to display the image.

You can follow the full discussion in this GitHub thread: https://github.com/timhagn/gatsby-background-image/issues/141

1
On

I'd recommend not using any external plugins for this but using CSS to achieve this. This way you don't have to learn any new third-party plugins and can use the knowledge you have about CSS. Here's an example from the docs: https://www.gatsbyjs.com/docs/how-to/images-and-media/using-gatsby-plugin-image/#background-images

import * as React from "react"
import { StaticImage } from "gatsby-plugin-image"

export function Hero() {
  return (
    <div style={{ display: "grid" }}>
      {/* You can use a GatsbyImage component if the image is dynamic */}
      <StaticImage
        style={{
          gridArea: "1/1",
          // You can set a maximum height for the image, if you wish.
          // maxHeight: 600,
        }}
        layout="fullWidth"
        // You can optionally force an aspect ratio for the generated image
        aspectRatio={3 / 1}
        // This is a presentational image, so the alt should be an empty string
        alt=""
        // Assisi, Perúgia, Itália by Bernardo Ferrari, via Unsplash
        src={
          "https://images.unsplash.com/photo-1604975999044-188783d54fb3?w=2589"
        }
        formats={["auto", "webp", "avif"]}
      />
      <div
        style={{
          // By using the same grid area for both, they are stacked on top of each other
          gridArea: "1/1",
          position: "relative",
          // This centers the other elements inside the hero component
          placeItems: "center",
          display: "grid",
        }}
      >
        {/* Any content here will be centered in the component */}
        <h1>Hero text</h1>
      </div>
    </div>
  )
}