React Routes - different style on body css tag

I have two routes in my React app: /a and /b .

For / a, I want the body css tag to have background-color: red; .

For / b, I want the body css tag to have background-color: blue; .

Both components a and b live in different .JSX files, and both import their own main.scss file, which defines their own body background-color .

However, since the entire application is compiled into a body tag, it seems that there is a conflict, and only one of the body tags is respected for both routes.

  <body> <script src="bundle.js" type="text/javascript"></script> </body> 

The reason I want to use the body tag, not just the div container, is because I want the background-color be visible when I view the borders of the page (bounce effect on Mac and iOS).

What is the right way to do this?

+14
source share
3 answers

This is because when you import your styles into your component without CSS modules, the styles are global, so your body style is defined twice (you can see all the styles in the <head> ).

enter image description here

You can fix this by setting the background color to your componentDidMount () component.

Example

 componentDidMount(){ document.body.style.backgroundColor = "red"// Set the style document.body.className="body-component-a" // Or set the class } 
+16
source

I agree with what QoP said, but as an addition to this, you should also make sure to use componentWillUnmount to set back what is usually outside this component.

for example: if usually for the entire application text alignment is left, but for one component you want it to be in the center, but after the component should return to the left position, you will do the following:

 componentDidMount() { document.body.style.textAlign = "center" } componentWillUnmount(){ document.body.style.textAlign = "left" } 
0
source

Add this code

 componentDidMount(){ document.body.style.backgroundColor = "white" } 

Hope to help.

0
source

All Articles