Fix TypeError: Cannot read properties of null (reading 'focus') in React
This error occurs when you try to call a method on a ref whose current value is still null, typically because the DOM element has not yet mounted or was conditionally rendered away. Fix it by adding a null check before accessing ref.current, or by calling ref methods inside useEffect where the DOM is guaranteed to be ready.
Reading the Stack Trace
Here's what each line means:
- at SearchBar (webpack-internal:///./src/components/SearchBar.tsx:12:18): SearchBar tries to call .focus() on ref.current at line 12, but the ref is still null because the DOM has not mounted yet.
- at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:16305:18): This is the render phase where refs are not yet attached to DOM elements.
- at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:20069:13): The component is being mounted for the first time, confirming the ref has not been assigned to a DOM node yet.
Common Causes
1. Accessing ref in the render body
Calling ref.current.focus() directly in the component body executes during the render phase, before React has attached the ref to the DOM element.
export default function SearchBar() {
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current.focus();
return <input ref={inputRef} placeholder="Search..." />;
}
2. Conditionally rendered element
The ref is attached to an element inside a conditional block, but code outside the block tries to access it when the element is not rendered.
export default function SearchBar({ isVisible }) {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return isVisible ? <input ref={inputRef} /> : null;
}
3. Ref forwarding missing
A parent component creates a ref and passes it to a child component that does not use forwardRef, so the ref stays null.
function CustomInput(props) {
return <input {...props} />;
}
export default function Form() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <CustomInput ref={inputRef} />;
}
The Fix
Move the ref.current.focus() call into a useEffect hook, which runs after the DOM has been painted and the ref has been attached. Add optional chaining as a safety guard in case the element is conditionally unmounted.
export default function SearchBar() {
const inputRef = useRef<HTMLInputElement>(null);
inputRef.current.focus();
return <input ref={inputRef} placeholder="Search..." />;
}
import { useRef, useEffect } from 'react';
export default function SearchBar() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} placeholder="Search..." />;
}
Testing the Fix
import { render, screen } from '@testing-library/react';
import SearchBar from './SearchBar';
describe('SearchBar', () => {
it('renders without crashing', () => {
render(<SearchBar />);
expect(screen.getByPlaceholderText('Search...')).toBeInTheDocument();
});
it('focuses the input on mount', () => {
render(<SearchBar />);
const input = screen.getByPlaceholderText('Search...');
expect(document.activeElement).toBe(input);
});
it('does not throw if input is not in the DOM', () => {
expect(() => render(<SearchBar />)).not.toThrow();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/react-ref-null-error,git add src/components/SearchBar.tsx src/components/__tests__/SearchBar.test.tsx,git commit -m "fix: move ref.focus() into useEffect to avoid null ref",git push origin fix/react-ref-null-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm the ref is properly accessed after mount.
- Open a pull request with the useEffect refactor.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the input autofocus works in staging.
Frequently Asked Questions
BugStack runs the fix through your test suite, validates that ref access is correctly deferred to useEffect, and confirms no other ref-dependent components break before marking it safe.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Yes. Callback refs fire immediately when the DOM node is attached, giving you a reliable reference without needing useEffect. They are useful for complex mounting scenarios.
Optional chaining (ref.current?.focus()) prevents the TypeError if the ref is null due to conditional rendering, instead of crashing the component.