Reputation: 31
I've been trying for hours to figure out how to get a background image component using GatsbyJS, I've tried multiple different ways to skin the cat but nothing I've tried seems to work. I'm not sure what I'm missing
I'm importing my BackgroundImage component, I'm running graphQL to get the filtered image from my images folder (graphQL is returning the correct image) I'm passing the data into the page and destructuring it
my index.js
import * as React from 'react'
import Layout from '../components/layout'
import Seo from '../components/seo'
import { Contact } from '../components/contactMe'
import { Link } from 'gatsby'
import { BackgroundImage } from '../components/backgroundImage'
// Step 2: Define your component
const IndexPage = ({ data }) => {
return (
<main>
<Layout>
<BackgroundImage imageData={data.backgroundImage.childImageSharp.gatsbyImageData}>
<h1>Welcome to Our Site</h1>
<p>This is the homepage with a custom background image.</p>
</BackgroundImage>
<Contact />
</Layout>
</main>
)
}
export const query = graphql`
query {
backgroundImage: file(relativePath: { eq: "process-background.webp" }) {
childImageSharp {
gatsbyImageData(layout: FULL_WIDTH, placeholder: BLURRED)
}
}
}
`
export const Head = () => <Seo title="Home Page" />
// Step 3: Export your component
export default IndexPage
I'm importing GatsbyImage and GetImage I'm creating a const to store the value the structure looks correct I'm not sure what I'm missing
my component
import { GatsbyImage, getImage } from "gatsby-plugin-image"
const BackgroundImage = ({ children, imageData }) => {
const image = getImage(imageData)
return (
<div>
<GatsbyImage
src={image} // Dynamically pass the image path here
alt="Background Image"
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
}}
imgStyle={{
objectFit: "cover", // Make the image cover the entire area
}}
layout="fullWidth" // This ensures the image covers the entire section
placeholder="blurred" // Optional: adds a blurred placeholder during loading
/>
<div className="background-content">{children}</div>
</div>
)
}
export default BackgroundImage
the error message I'm getting is the following
One unhandled runtime error found in your files. See the list below to fix it:
Error in function IndexPage in ./src/pages/index.js:89 Cannot read properties of undefined (reading 'backgroundImage')
./src/pages/index.js:89 Open in Editor 87 | 88 |
89 | | ^ 90 |
Welcome to Our Site
91 |This is the homepage with a custom background image.
92 |
Upvotes: 0
Views: 28