Adding styles and other attributes to the <body> tag in React.
I am currently trying out small examples in react, when I wanted to add a class to the body of the React app. Adding a class to the document is not straight-forward in React apps. We need to do it in a different way, since <body> lies outside the ‘body’ of a React app.
Consider enabling dark mode of the application. We need to add a class to the <body>. Let us see how to do that:
.dark-mode {
color: white;
background-color: black;
}
We are adding the required properties for the dark mode in the CSS file.
Let us add a basic checkbox which will enable the dark mode when the checkbox is enabled and vice versa when disabled. We will add the class to the <body> when the checkbox is enabled.
render() {
return (
<div className="App">
<input
type="checkbox"
defaultValue={this.state.isDarkMode}
onChange={this.setDarkMode}
/>
Set dark mode.
</div>
);
}
setDarkMode = (e) => {
this.setState({
isDarkMode: e.target.checked
});
if (e.target.checked) {
document.body.classList.add("dark-mode");
} else {
document.body.classList.remove("dark-mode");
}
};
Normally, the page would like the below:
When the checkbox is checked, the dark mode will be enabled as below:
Thus, we are manipulating the classList of the <body> tag. The same way we can add other attributes and styles.
document.body.classList.add("dark-mode");
document.body.style.fontSize = "2rem";
document.body.style.overflow = "hidden";
document.body.<userDefinedAttribute> = value;
Although this is easy to do, it is not a correct method. Always have a <div> inside the document's body and handle the top-level changes using that.
<html>
<head>
</head>
<body>
<div id="root">
<!-- Root Component -->
</div>
</body>
</html>