React: Changing backgrounds for different components

React: Changing backgrounds for different components


Hello, so I just want to check if I’m going about this completely wrong or if I’m on the right track.
I’m super new to react and thought I’d practice and rebuild my portfolio with it as a SPA (I’ve already made a couple others that work great). I have a Navbar component that is always visible and then directly below it my ‘home’ component renders. When you click on Projects or About on the Navbar, then that component loads instead and replaces home, but the Navbar never re-renders. This all works flawlessly as it should.
Anyways I want it so my home page always has a full screen background and then when you change to Projects or About the background turns white. The way Ive done it is setting the body background to an image in my CSS file and then using:
componentDidMount(){ '#fff'; }
on both the Projects and About component to change the body background to white, and then on the Home component I’ve used:

const mainBg = {
  backgroundImage: 'url("./images/bg.jpg")',
  backgroundRepeat: 'no-repeat',
  backgroundSize: 'cover',
  backgroundPosition: 'center',

and then to change the body background back to the image:

componentDidMount(){ {mainBg};

It works exactly as I hoped it would, but I have no clue as to whether it is correct or not, I feel like it probably isn’t and that there is a better way, in my head I just see these componentDidMount layering up like a cake. I’ve tried setting the specific component background but then it doesn’t cover the whole screen, just up to the Navbar, which I expected.
Anyhoo all thoughts welcome.


Personally I would avoid modifying the document object directly from within React because it just seems dirty to me. If you want to do this the “React way” I would put the function for changing backgrounds into the root component of the app, and make sure the div which the app is mounted to is 100% of both height and width of the page (also make sure your html element is at 100% of the page). Then you can style the root component. You can pass this function via a prop to navbar, so it can call it and change the background.


Hahaha I forgot I had asked this all those months ago when I first started poking react! Thank you for the response :smiley: As I now actually work it, yes I would probably do something like you suggested, but perhaps this post will help a new newbie out :smiley: