Sometimes, we want to set HTML body element styles from within a React component.
In this article, we’ll look at how to set HTML body element styles from within a React component.
Set HTML body Element Styles from within a React Component
To set HTML body element styles from within a React component, we can set the document.body.style
properties to the values we want.
For instance, we write:
import React, { useEffect } from "react";
export default function App() {
useEffect(() => {
document.body.style.backgroundColor = "yellow";
return () => {
document.body.style.backgroundColor = "white";
};
}, []);
return <div>hello world</div>;
}
We set document.body.style.backgroundColor
to the value we want in the useEffect
hook so that it’s set to the value we want when the component is rendered.
And we set the 2nd argument of the hook to an empty array so that the background color is only set when the component is first rendered.
Also, we return a function that sets the background color when we unmount the component in the useEffect
callback.
Now we should see the page has a yellow background.
Conclusion
To set HTML body element styles from within a React component, we can set the document.body.style
properties to the values we want.
2 replies on “How to Set HTML body Element Styles from within a React Component?”
Is this implementation of adding styles to the document frowned upon? Is it viewed as an okay practice? I don’t see it used anywhere in my company’s project that was built by a outsourced development company. I am the only front-end developer right now and want to use this as a way of adding {cursor: ‘wait’} to bypass some styles they have implemented for a component.
If it’s dynamic and it’s applied throughout the app, then it’s fine to do so.