I have googled around and tried various solutions but cannot seem to get my app to work correctly. I want my app to show a different background image based on what component is rendered on the screen. I am implementing this app with React Router and all styling is done with Material UI.
As suggested in other similar posts, I have tried to import the background images to each component class individually and use className's to render the background image (attempt shown below). However, when I try the solution below, I can't seem to get any background image to render. In fact, the only way I can get any background image to render is via my App.css code below. Doing this however sets a constant background image for the entire app, which leaves me back at square one.
App.js
class App extends React.Component {
render() {
return (
<div>
<Router history={history}>
<NavBar />
<Route path="/" exact component={Home} />
<Route path="/contact" exact component={Contact} />
</Router>
</div>
);
}
}
the next two code segments show my attempt at showing different background images based on the component rendered.
Home.js
import image from "../relative/path.jpeg";
const useStyles = makeStyles((theme) => ({
home_scene: {
backgroundImage: `url(${image})`,
},
}));
const Home = () => {
const classes = useStyles();
return (
<div className={classes.home_scene}>
.... a lot of code here, left out for readability
</div>
Contact.js
import image from "../different/image's/relative/path.jpeg";
const useStyles = makeStyles((theme) => ({
contact_scene: {
backgroundImage: `url(${image})`,
},
}));
const Contact = () => {
const classes = useStyles();
return (
<div className={classes.contact_scene}>
.... a lot of code here, left out for readability
</div>
When attempting this, I fail to get any background image at all. The only way I can get any background image to show is by doing the following, which leaves one static background throughout the whole app.
App.css
body {
background: url(/path/to/file) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Perhaps there is a way to render a background image with react router based on the current route, but I am not sure how to do that either. Any help would be greatly appreciated