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.