Borislav Hadzhiev
Wed Apr 27 2022·2 min read
Photo by Jennifer Grey
To set styles on the body element in React:
document.body
in useEffect
or an event
handler.style
property to set styles on the body element.document.body.style.backgroundColor = 'lime'
.import {useEffect} from 'react'; import './App.css'; export default function App() { useEffect(() => { // 👇 add class to body element document.body.classList.add('bg-salmon'); // 👇️ set style on body element document.body.style.backgroundColor = 'salmon'; return () => { // 👇️ optionally remove styles when component unmounts document.body.style.backgroundColor = null; document.body.classList.remove('bg-salmon'); }; }, []); return ( <div> <h2>Hello world</h2> </div> ); }
And here is the css
file for the example.
.bg-salmon { background-color: salmon; color: white; }
We can access the body
element on the document
object.
You can use the style object to read an element's styles or set new styles on the element.
If you need to add a class to the body element, use the classList.add method.
We passed an empty dependencies array to the
useEffect hook
because we only want to set styles on the body
element once - when the
component mounts.
If you need to remove the styles when the component unmounts, return a cleanup
function from the useEffect
hook.
useEffect(() => { // 👇 add class to body element document.body.classList.add('bg-salmon'); // 👇️ set style on body element document.body.style.backgroundColor = 'salmon'; return () => { // 👇️ optionally remove styles when component unmounts document.body.style.backgroundColor = null; document.body.classList.remove('bg-salmon'); }; }, []);
To remove a style, you can just set it to null
.
You can also set classes to the body element when an event is triggered, e.g. a button is clicked.
export default function App() { const handleClick = () => { document.body.style.backgroundColor = 'salmon'; document.body.style.color = 'white'; }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }
We set the onClick
prop on the button element, so every time it is clicked,
the handleClick
function gets invoked.
If you need to toggle styles on the body element when an event occurs, conditionally check whether the styles are already present and remove them if they are, otherwise set the styles.
export default function App() { const handleClick = () => { if (document.body.style.backgroundColor) { document.body.style.backgroundColor = null; document.body.style.color = null; } else { document.body.style.backgroundColor = 'salmon'; document.body.style.color = 'white'; } }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }
If the backgroundColor
style is already set on the body element, we remove it
by setting it to null
, otherwise we set it to salmon
.