Setting Background Color of Body Dynamically in React

CSS Custom Property

: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)
}

Using the function

Import the function in a component using,

import setBodyColor from './setBodyColor'
const HomePage = () => {    
useSetBodyColor({color: "#ffffff"})
return (
<>...</>
)
}
export default HomePage

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Murtuza

Murtuza

Full Stack Developer | Content Creator | Technical Writer