DEV Community

Murtuzaali Surti
Murtuzaali Surti

Posted on • Edited on • Originally published at syntackle.live

Setting Background Color of Body 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 or not, but let's have a 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);
}
Enter fullscreen mode Exit fullscreen mode

Creating a Function

Create a file named setBodyColor.js 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)
}
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Change the relative url ./setBodyColor as per your folder structure.

Use it in your functional component,

const HomePage = () => {

    setBodyColor({color: "#ffffff"})

    return (
        <main>
        ...
        </main>
    )
}

export default HomePage
Enter fullscreen mode Exit fullscreen mode

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 is do your own research.

Also, if you have any better solution, feel free to ping me on twitter.

Signing off.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

This is just a plain function, it's not even a hook. You've described how to write and import a function that changes a CSS variable. The fact that you mention React is irrelevant.

Collapse
 
murtuzaalisurti profile image
Murtuzaali Surti

I agree, updated.