Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Routes - different styling on body css tag

Tags:

css

sass

reactjs

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

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

For /b, I want the body css tag to have a 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 respective body background-color.

However, since the entire app is compiled into the body tag, there seems to be 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 it on the body tag and not just a container div is that I want the background-color to be visible when I scroll outside the bounds of the page (the bounce effect on Mac and iOS).

What's the proper way to do this?

like image 783
Snowman Avatar asked Jun 05 '16 12:06

Snowman


2 Answers

That's happening because when you import your styles in your component without CSS Modules, the styles are global so your body style is defined two times (you can see all the styles in the <head> tag).

enter image description here

You can fix that by setting the background color in your component componentDidMount() method.

Example

componentDidMount(){
    document.body.style.backgroundColor = "red"// Set the style
    document.body.className="body-component-a" // Or set the class
}
like image 97
QoP Avatar answered Oct 16 '22 11:10

QoP


I agree with what QoP said but, as an add on to that, you should also make sure to use componentWillUnmount to set it back to whatever it normally is outside that component.

for example: if normally for the whole application text-align is left but for one component you want it to be center, but after the component it needs to return to being left, you will do the following:

componentDidMount() {
    document.body.style.textAlign = "center"
  }

  componentWillUnmount(){
    document.body.style.textAlign = "left"
  }
like image 2
Margo Henning Avatar answered Oct 16 '22 13:10

Margo Henning