I'm encountering a challenge while trying to set unique background images for different pages in my React multipage web application. My approach involves creating separate CSS files for each page and applying distinct background images to the background-image property of the body element in these files. However, upon navigating to different pages, only one of the background images is being applied across all the pages, instead of each page displaying its designated background image.
I've ensured that the CSS files are correctly imported and applied to their respective pages, and I've verified that the correct path to each image is specified in the CSS. Despite this, the issue persists, and I'm unable to figure out why the background images are not being displayed as intended on each page.
Any insights or suggestions on how to resolve this issue and successfully set unique background images for different pages in a React multipage web app would be greatly appreciated. Thank you.
In attempting to set unique background images for different pages in my React multipage web app, I followed these steps:
- Created separate CSS files for each page.
- Specified distinct background images using the background-image property in each CSS file.
- Imported and applied the CSS files to their corresponding React components/pages.
What I expected was that upon navigating to each page, the background image specified in the respective CSS file would be applied to the body element, thereby displaying a unique background image for each page.
However, despite following these steps, I observed that only one of the background images is consistently being applied across all pages, rather than each page displaying its designated background image as intended. This outcome is contrary to my expectations, and I'm seeking guidance on how to troubleshoot and resolve this issue effectively.
I can give you 2 potentials solutions:
First solution
You could try to create an hook that basically updates the body applying a different background url.
Example:
useBackgroundImage.js
Home.jsx
About.jsx
Check out this sandbox to see a working example.
Second solution
As second solution I would suggest you to create a
Layoutcomponent that wraps every page component and applies a background image to the body in the same way of the hook shown before.Example:
Layout.js
Home.jsx
About.jsx
Check out this other sandbox for a working example.