0

Creating a React component where I am trying to use css property of background-color to fall back when background-image is null as I could see one of the SO post here. The code only works if there is any image, but when there is no image it doesn't fall back to background-color and shows an error undefined:1 GET http://localhost:3000/undefined 404 (Not Found). What am I missing?

const BoxModule = ({
  backgroundColor,
  BackgroundImage,

}) => {

const imageFormats = BackgroundImage?.formats;
const imageSrc = formatImage({ formats: imageFormats });

if (!BackgroundImage || !BackgroundImage?.url) {
  return null;
}

return (
 <Section
   backgroundColor={backgroundColor}
   backgroundImageUrl={imageSrc}
 >
 ...
 </Section>
); 

export default BoxModule;
 
const Section = styled(Section)`
  background-color: ${(p) => p.backgroundColor};
  background-image: ${(p) => `url('${p.backgroundImageUrl}')`};
  background-repeat: no-repeat;
`;

[Updated error trace]

I can only see the error as shown below:

enter image description here

Is this error because the code is trying to process the image which fails due to the null value and therefore doesn't fall back to bacground-color?

PineCone
  • 2,193
  • 12
  • 37
  • 78

1 Answers1

0

Actually the code was enough to fallback on background-color. Issue was not this, something else. So to answer this particular issue the following code is enough. Don't even need and null conditional check for the background-image.

const Section = styled(Section)`
background-color: ${(p) => p.backgroundColor};
background-image: ${(p) => `url('${p.backgroundImageUrl}')`};
background-repeat: no-repeat;
`;
PineCone
  • 2,193
  • 12
  • 37
  • 78