Reputation: 32071
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?
Upvotes: 25
Views: 10292
Reputation: 191
or, if youre using functional components you can do the same with useEffect...
useEffect(() => {
document.body.className = 'class-name';
}, []);
Upvotes: 4
Reputation: 2167
Add this code
componentDidMount(){ document.body.style.backgroundColor = "white" }
Hope to help.
Upvotes: 0
Reputation: 21
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"
}
Upvotes: 2
Reputation: 28397
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).
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
}
Upvotes: 22