React Router allows us to build single page application’s with navigation without having to refresh the page as the user navigates to different pages throughout the site. This prevents the client from having to make additional HTTP requests, thus increasing the performance of your website and creating a seamless user experience.
How to Change the Background Color When a New Component Loads into the Viewport
One of the problems I was having when using React Router was changing the background color of the body when loading a new component from my Route’s.
class App extends React.Component {
render() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route exact path="/blog" component={Blog} />
<Route path="/blog/:id/:slug" component={BlogDetails} />
</Router>
);
}
}
When the new route would render into the viewport, the styles would only apply to the component that was being loaded and not the body. After countless hours looking online, I checked out Dan Abramov’s Overreacted blog and saw a feature on his page that allows users to change the theme from light to dark. After inspecting his code, I found that when toggling the theme button, the body’s classname would change.
I decided to implement this solution on my site by calling the componentDidMount() lifecycle method. On each of my components, I called the method and targeted the document.body.className and changed it:
componentDidMount() {
document.body.className = "home";
}
Next, in my index.css file, I added my classname selectors and applied the appropriate properties:
.home {
background: #fff;
}
.blog {
background: #282c35;
}
.blogdetails {
background: #282c35;
}
VoilĂ .