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
Related: React Interview Questions