Setting Background Color of Body Dynamically in React
Learn how to set the application's body background color dynamically in React.
In a single-page application, you only have one body
element, and although you can specify the background color of body
in a global stylesheet, it's not easy to update the background color dynamically for different pages in your website.
I encountered this issue and immediately googled some solutions, but I wasn't satisfied with them.
So, I went on to code a hacky but working patch using CSS custom properties. I don't know if it's a recommended practice, but let's look at it.
CSS Custom Property
Set a custom property in your :root
or html
element style which contains a default color value. Specify this styling in a global stylesheet. In your case it will probably be index.css
.
:root {
--bodyColor: "#000000";
}
body {
background-color: var(--bodyColor);
}
Creating a function
Create a file named setBodyColor
in the src
directory, which contains a function ready to be exported. The function is shown below:
export default function setBodyColor({color}) {
document.documentElement.style.setProperty('--bodyColor', color)
}
In this way, you can modify the value of the CSS custom property --bodyColor
.
Using the function
Import the function in a component using,
import setBodyColor from './setBodyColor'
Change the relative url
as per your folder structure.
Use it in your functional component,
const HomePage = () => {
setBodyColor({color: "#ffffff"})
return (
<>...</>
)
}
export default HomePage
You can use this function in multiple components and pass a color to modify the background color of the body.
Note that you must call the function on every page or component to set the background color of the body. Otherwise, it will just take the value of the background color of the previous page.
This workaround isn't limited to background-color
property. You can set as many custom properties as you want. But, as I said earlier, I don't know if this is a foolproof technique, so the best thing you can do for your case does your own research. Also, if you have any better solution, feel free to ping me on twitter.
Signing off.