TypeError: Cannot read properties of null (reading 'addEventListener')
TypeError: null is not an object (evaluating 'x.name')
Youβre trying to access a property or call a method on null. The variable exists but has no value.
Fix 1: DOM Element Not Found
// β Element doesn't exist (yet)
const btn = document.getElementById('submit');
btn.addEventListener('click', handler); // π₯ btn is null
// β
Check if element exists
const btn = document.getElementById('submit');
if (btn) {
btn.addEventListener('click', handler);
}
// β
Or wait for DOM to load
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('submit').addEventListener('click', handler);
});
Fix 2: Script Loaded Before HTML
<!-- β Script runs before the element exists -->
<script src="app.js"></script>
<button id="submit">Click</button>
<!-- β
Put script at the end or use defer -->
<button id="submit">Click</button>
<script src="app.js"></script>
<!-- Or use defer -->
<script defer src="app.js"></script>
Fix 3: API Returned Null
// β Assuming API always returns data
const user = await fetchUser(id);
console.log(user.name); // π₯ If user is null
// β
Handle null response
const user = await fetchUser(id);
if (!user) {
console.log('User not found');
return;
}
console.log(user.name);
Fix 4: React β Ref Not Attached Yet
// β Accessing ref before component mounts
const inputRef = useRef(null);
inputRef.current.focus(); // π₯ null on first render
// β
Use useEffect
useEffect(() => {
inputRef.current?.focus();
}, []);
Fix 5: Optional Chaining
// β Deep property access
const city = user.address.city; // π₯ If address is null
// β
Optional chaining
const city = user?.address?.city ?? 'Unknown';
Fix 6: querySelector Returns Null
// β Selector doesn't match anything
const el = document.querySelector('.nonexistent');
el.style.color = 'red'; // π₯ null
// β
Guard against null
const el = document.querySelector('.nonexistent');
if (el) el.style.color = 'red';
Related resources
- Cannot read properties of undefined fix
- React cannot read null fix
- TypeScript object is possibly undefined fix
Related: JavaScript Array Methods Cheat Sheet Β· React Interview Questions Β· React White Screen Blank Page Fix