
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeIn React, you generally cannot add a ref to the <body> element using React Helmet or similar libraries. This is because refs in React are designed to work with React-managed DOM elements, and the <body> tag exists outside of React's render tree.
However, you have a few alternatives:
1. Direct DOM access (simplest approach)
Since the <body> element always exists, you can access it directly without needing a ref:
useEffect(() => {
const bodyElement = document.body;
// Do whatever you need with the body element
bodyElement.style.overflow = 'hidden'; // example
return () => {
// cleanup if needed
};
}, []);2. Use document.querySelector in a useEffect
If you need to perform operations on the body element when your component mounts:
useEffect(() => {
const body = document.querySelector('body');
// Your operations here
}, []);3. For attributes, use Helmet's bodyAttributes
React Helmet actually has a bodyAttributes prop that lets you add attributes to the body tag:
import { Helmet } from 'react-helmet';
<Helmet>
<body className="my-custom-class" data-theme="dark" />
</Helmet>Why refs don't work with <body>:
<body> element exists outside React's component tree (it's part of the static HTML)<head> and body attributes, but it doesn't create React elements that can hold refsIf you're working within Sanity Studio and need to customize the body element, direct DOM access in a useEffect hook is your best bet. Just make sure to clean up any modifications when your component unmounts to avoid side effects.
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store