Can I add a ref to the body element in Sanity?
In 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>:
- Refs are React's way of accessing DOM nodes that React creates and manages
- The
<body>element exists outside React's component tree (it's part of the static HTML) - React Helmet works by manipulating the DOM directly for elements in
<head>and body attributes, but it doesn't create React elements that can hold refs
If 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.
Show original thread2 replies
Sanity – Build the way you think, not the way your CMS thinks
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.