I found a problem, that I can’t explain myself. Short story long: I tried to build a native draggable slider with react and positioned it in the middle of the screen. At least in my Codesandbox file. There I used this code:
const windowWidth = window.innerWidth / 2;
const itemWidth = track.firstChild.offsetWidth / 2;
const offsetPercent = ((windowWidth - itemWidth) / window.innerWidth) * 100;
track.style.left = `${offsetPercent}%`;
In codesandbox it works fine as hell. Everything like I like it to be. Now I wanted to add this test code to my real project. Build with NextJs, React & IDE VS Code.
But there I’ll always get this error: "TypeError: Cannot read properties of null (reading ‘offsetWidth’)" see here
I can’t explain myself why. The whole code is the same like in Codesandbox.
Here’s a link to the codesandbox
Like I said, i tried the code in Codesandbox, where it runs perfectly. But in my local IDE, VS Code I get this error message. Therefore it’s the same code I can’t explain it myself, why I’m getting the error..
2
Answers
Try to use optional chaining, using
?
.If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
In frameworks like Next, which is competely SSR, components are rendered twice – once on the server and once in the browser. For this reason, you must make your components server-safe. For example,
window
is not available in the server. And, likely, whatevertrack
is could also not be found.Even if it could, and even if you’re on a browser,
track
could end up being empty.By using
track.firstChild.offsetHeight
you expectfirstChild
to exist – but what if, for any reason, it doesn’t?To do this, consider it not being there in your code.
Or, to be more concise, use optional chaining: