Despite trying several ways to load the image for the backgroundImage property, it never shows up in page. Loading external images (for example from google) works as expected.
I tried:
backgroundImage: `url(${Papyrus})`
backgroundImage: "url(" + Papyrus + ")"
backgroundImage: "url(../../assets/images/papyrus.png)"
backgroundImage: Papyrus
backgroundImage: "url(\"../../assets/images/papyrus.png\")"
backgroundImage: "url(assets/images/papyrus.png)"
NONE of them work. The image is loaded when I look at my network audit, I can find it in the static folder, but it's never displayed.
App.tsx
import React from 'react';
import makeStyles from './app-styles';
import {Container} from "@material-ui/core";
import Description from "../description/description";
const App: React.FC = () => {
const classes = makeStyles();
return (
<div className="App">
<Container maxWidth={"xl"}>
<div className={classes.row}>
<Description/>
</div>
</Container>
</div>
);
};
export default App;
description.tsx
import * as React from "react";
import makeStyles from './description-styles';
interface DescriptionProps {
}
const Description: React.FC<DescriptionProps> = () => {
const classes = makeStyles();
return (
<div className={classes.descriptionCard}>
<p>Some text</p>
</div>
)
};
export default Description;
description-styles.tsx
import makeStyles from "@material-ui/core/styles/makeStyles";
import Papyrus from "../../assets/images/papyrus.png";
export default makeStyles(theme => ({
descriptionCard: {
backgroundImage: `url(${Papyrus})`,
// margin: 'auto',
height: '25vh',
width: 'calc(20vw * 0.54 - 2%)',
borderRadius: 8,
display: 'flex',
marginLeft: '10px',
marginTop: '10px'
},
text: {
}
}))
Method 2: Using external CSS: In this method, we add an external CSS file to set a background image for the react component. In App. js, we will add a simple div element with the className attribute. Also, we import an external CSS file to set a background image for the div element.
To display an image from a URL, use the img tag and set its src prop to the complete URL of the image. Optionally set the alt prop to a short description of the image. Copied!
Add some additional properties to the background image and it will work -
descriptionCard: {
backgroundImage: `url(${Papyrus})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
// margin: 'auto',
height: '25vh',
width: 'calc(20vw * 0.54 - 2%)',
borderRadius: 8,
display: 'flex',
marginLeft: '10px',
marginTop: '10px'
}
I'm not sure why we need these additional properties (maybe someone could add to the answer), but sometimes the image needs certain behaviour to be defined, like size, position, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With