TypeError: Cannot read properties of null (reading 'value')
You’re accessing a property on something that’s null — usually a ref that hasn’t attached yet or state that hasn’t loaded.
Fix 1: Check ref before using it
// ❌ Ref is null on first render
const inputRef = useRef(null);
console.log(inputRef.current.value); // null!
// ✅ Check first
const inputRef = useRef(null);
if (inputRef.current) {
console.log(inputRef.current.value);
}
// ✅ Or use in useEffect (runs after DOM is ready)
useEffect(() => {
console.log(inputRef.current.value); // Safe here
}, []);
Fix 2: Handle null state
// ❌ Data is null before fetch completes
const [user, setUser] = useState(null);
return <p>{user.name}</p>; // null!
// ✅ Guard against null
const [user, setUser] = useState(null);
if (!user) return <p>Loading...</p>;
return <p>{user.name}</p>;
// ✅ Or use optional chaining
return <p>{user?.name}</p>;
Fix 3: DOM element doesn’t exist
// ❌ getElementById returns null if element isn't rendered
const el = document.getElementById('my-element');
el.style.color = 'red'; // null!
// ✅ Use refs instead of getElementById in React
const elRef = useRef(null);
return <div ref={elRef}>...</div>;
Fix 4: Conditional rendering removed the element
// ❌ Ref becomes null when element is conditionally hidden
{showInput && <input ref={inputRef} />}
// Later: inputRef.current is null when showInput is false
// ✅ Always check
if (inputRef.current) {
inputRef.current.focus();
}
See also: Cannot read property of undefined fix | React Hooks cheat sheet