document.getElementById returns null in a Next.js component although the id is in the JSX
document.getElementById('my-id') returns nullShort answer
getElementById only finds elements that are already in the document when it is called. In a React component that is not the case during rendering, and not for elements that appear later or live inside a child component. Replace the lookup with a ref, and read it inside an effect or an event handler.
Fix it fast
1Find out which cause you have
Open the page in the browser, wait until it has fully loaded, and run the lookup by hand in the DevTools console. If it returns the element now, your code runs too early. If it still returns null, the element is not in the document at all.
document.getElementById('my-id')2Match what you see, then jump to its fix
- 1
The call sits in the body of the component or at the top of the module, and it returns null on the first renderThe lookup runs while the component rendersFix - 2
The element sits behind a condition, a loading state or fetched data, and the lookup runs once on mountThe element is rendered later than the code that looks for itFix - 3
You give an id or a ref to a custom component such as <MyInput />, and the lookup finds nothingThe element belongs to a child componentFix
- 1
What does the error look like?
document.getElementById('my-id') returns null
Cause 1 of 3
The lookup runs while the component renders
1Check
During the first render React has not created any DOM nodes yet, and on later renders the DOM has not been updated yet. Reading the DOM in that phase finds nothing, or finds the old version.
grep -rn "getElementById" app components src 2>/dev/null2Fix
Attach a ref to the element and read ref.current from an effect or an event handler, which run after React has put the element in the page.
'use client'
import { useEffect, useRef } from 'react'
export default function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
inputRef.current?.focus()
}, [])
return <input ref={inputRef} />
}3Verify
Reload the page: the input has focus and nothing is read from the DOM during render.
# browser: reload and check that the input is focusedConfirmed by react.dev
Cause 2 of 3
The element is rendered later than the code that looks for it
1Check
An effect with an empty dependency array runs once, right after the first commit. If the element only appears after a state change, the lookup has already happened, and getElementById reports null for an element that is not in the document yet.
grep -rn -B3 -A6 "useEffect" components/panel.tsx2Fix
Keep a ref to the element and put the state that shows it in the dependency list of the effect. React runs the effect again after each commit where that value changed, by which time the element exists.
'use client'
import { useEffect, useRef, useState } from 'react'
export default function Panel() {
const [open, setOpen] = useState(false)
const panelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (open) panelRef.current?.scrollIntoView()
}, [open])
return (
<>
<button onClick={() => setOpen(true)}>Open</button>
{open && <div ref={panelRef}>Details</div>}
</>
)
}3Verify
Click the button; the panel appears and scrolls into view without a null error.
# browser: click Open and watch the console stay cleanConfirmed by react.dev
Cause 3 of 3
The element belongs to a child component
1Check
A component is not a DOM element. Only what it returns reaches the page, so a prop you hand to <MyInput /> is invisible unless the component passes it on to a real element.
grep -rn "MyInput" app components src 2>/dev/null2Fix
In React 19, ref is an ordinary prop. Let the child pass it to its DOM element, and keep the ref in the parent.
function MyInput({ ref }: { ref?: React.Ref<HTMLInputElement> }) {
return <input ref={ref} />
}
// in the parent
const inputRef = useRef<HTMLInputElement>(null)
return <MyInput ref={inputRef} />3Verify
In an effect or handler, inputRef.current is the input element, not null.
# console.log(inputRef.current) inside the handlerConfirmed by react.dev
How do I stop it coming back?
- Do not search the page by id from inside React components: keep a ref to the element you own.
- Read refs only in effects and event handlers, never while rendering.
- When the element is optional or arrives late, list the value that shows it in the effect's dependency array.
- When you pass a ref across components, check that the child hands it to a real DOM element.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
Next.js stops with 'document is not defined' while it renders on the server
ReferenceError: document is not defined
Next.js renders your components on the server first, where there is no document.
3 causes, each with a fixWeb apps
React hydration failed: the server HTML and the first browser render differ
Text content does not match server-rendered HTML
Hydration fails when the first render in the browser produces different HTML from the HTML the server sent.
5 causes, each with a fixWeb apps
ESLint says an element in a list is missing its key prop
react/jsx-key
react/jsx-key fires when an element returned from map, Array.from or an array literal has no key.
3 causes, each with a fixWeb apps
There is no tailwind.config.js after installing Tailwind 4 and HeroUI in Next.js
HeroUI components render unstyled
Nothing is broken: Tailwind CSS 4 is configured in CSS and no longer creates tailwind.config.js.
3 causes, each with a fixWeb apps
react-i18next shows the wrong plural form for a count, or prints the key instead of the text
t('item') prints the key item instead of a translated sentence
i18next picks a plural from the count option and looks for keys ending in _one, _other and so on.
4 causes, each with a fixWeb apps
useSession throws because there is no SessionProvider above it
[next-auth]: `useSession` must be wrapped in a <SessionProvider />
useSession reads the session from React Context, and SessionProvider is what creates that context.
3 causes, each with a fix