Reputation: 476
I have a rather simple question about React, but I wanna see what the best practice is for this kind of situation.
How do you change the body background color, according to the page you are in? Do you set a CSS rule for the body background color in a CSS file for each page and import it in the component? Will the above work or do I need to add a CSS class to the body tag using componentDidMount, and remove it in componentWillUnmout?
Which one is the preferred way? I noticed that if you imported some CSS in one page, it will remain active even after you navigate to a new url. So, maybe I need to use componentDidMount/componentWillUnMount, is that correct?
Upvotes: 1
Views: 5881
Reputation: 2087
Yes,we can change the background-color
of body
based on the route change.Determine the page you are in by using componentWillReceiveProps
or componentDidUpdate
lifecycle method and get the route name using props.location.pathname
provided by react-router-dom
.If your route composes of params
,then just replace the props.location.pathname
by props.match.params.customparam
componentDidMount(){
document.body.style.background = "red";
}
componentWillReceiveProps(nextProps){
if(this.props.location.pathname !== nextProps.location.pathname){
const currentRoute = nextProps.location.pathname;
switch(currentRoute){
case "\a": document.body.style.background = "blue";
break;
case "\b": document.body.style.background = "green";
break;
default : document.body.style.background = "red";
}
}
}
Upvotes: 1