I'm working on a Gatsby project and I've run into a frustrating problem. I have a component that receives a relative path to an image as props, which I then use to populate a background-image property:
import React, { FC } from 'react'
// Prop typings
type TProps = {
imageUrl: string;
}
const MyComponent: FC<TProps> = ({ imageUrl }) => {
const divStyles = {
backgroundImage: `url(${imageUrl})`,
}
return (
<div style={divStyles}></div>
)
}
export default MyComponent
The relative path passed in imageUrl references an image in my src directory. I've double-checked that the path is correct and the image exists, yet the image won't appear when the component renders.
I can set the background image successfully using CSS, but it fails when the image path is passed as a prop. I've also tried setting the image URL using Gatsby's withPrefix utility function, but no dice.
Am I doing something wrong, or is it just impossible to define a background image in Gatsby from props?
If you want to show an image like this it's not a Gatsby issue, but a React related question.
This is the right way to import an image in React and pass it down with props:
// Parent component
import image from "../relative/path/to/image";
<MyGreatComponent image={image} />
// MyGreatComponent
export default function MyGreatComponent({ image }) {
const divStyles = {
backgroundImage: `url(${image}`,
}
return (
<div style={divStyles}></div>
)
}
Reference: https://create-react-app.dev/docs/adding-images-fonts-and-files/
Happy hacking!
Am I doing something wrong, or is it just impossible to define a background image in Gatsby from props?
You should be able to, as any other React project.
The only problem I think you may be facing is the relativity of the paths. Without knowing the current offending path (imageUrl) or how's your project structure it's difficult to guess but try something like:
import React, { FC } from 'react'
// Prop typings
type TProps = {
imageUrl: string;
}
const MyComponent: FC<TProps> = ({ imageUrl }) => {
const divStyles = {
backgroundImage: `url(../${imageUrl})`,
}
return (
<div style={divStyles}></div>
)
}
export default MyComponent