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:
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
?
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;
`;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.