gatsby-image: how to import the processed image into css and use it with background-image property

Viewed 2389

I sucessfully implemented the gatsby-image into my project and replace lots of img tag that are used in my components. But now im trying to optimized the background image for some of my component but i dont know how since using gatsby-image would generate a new img tag, and i cant use that to style as a background for say a div element. can s1 show me how i can use the generated images with css. Here's my code:

const HeaderlineSection = ({headerOne}) => {
  return(
    <div className="header-back" ></div>
  )
}

export const query = graphql`
  query IndexPageQuery {
    headerOne: imageSharp(id: { regex: "/header_one.jpg/" }) {
      sizes(maxWidth: 1200 ) {
        ...GatsbyImageSharpSizes
      }
    }
  }

previously, in my css i use a non optimized image for backgroud-image:

.header-back {
  background: url(../images/header_one.jpg) 50% 0 no-repeat;
  height: 470px;
  width: 100%;
}
1 Answers

I am using gatsby-background-image plugin for that. Here is one exemple of how you can use it :

import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import styled from 'styled-components'

import BackgroundImage from 'gatsby-background-image'

const BackgroundSection = ({ className }) => (
    <StaticQuery query={graphql`
      query {
        desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) {
          childImageSharp {
            fluid(quality: 100, maxWidth: 4160) {
              ...GatsbyImageSharpFluid_withWebp
            }
          }
        }
      }
    `}
     render={data => {

       const imageData = data.desktop.childImageSharp.fluid
       return (
          <BackgroundImage Tag="section"
                           className={className}
                           fluid={imageData}
                           backgroundColor={`#040e18`}
          >
            <h1>Hello gatsby-background-image</h1>
          </BackgroundImage>
       )
     }
     }
    />
)

const StyledBackgroundSection = styled(BackgroundSection)`
  width: 100%;
  background-repeat: repeat-y;
`

export default StyledBackgroundSection

The code is self-explanatory, but basically, element will be replaced with the element that you select in the Tag attribute and will have the background image set to the one selected with the graphql imageSharp query.

Related