skip to Main Content

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


  1. 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.

    const windowWidth = window.innerWidth / 2;
    const itemWidth = track?.firstChild?.offsetWidth / 2;
    const offsetPercent = ((windowWidth - itemWidth) / window.innerWidth) * 100;
    
    track.style.left = `${offsetPercent}%`;
    
    Login or Signup to reply.
  2. 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, whatever track 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 expect firstChild to exist – but what if, for any reason, it doesn’t?

    To do this, consider it not being there in your code.

    const child = track.firstChild;
    if (!firstChild) return;
    const itemWidth = firstChild.offsetWidth / 2;
    

    Or, to be more concise, use optional chaining:

    const itemWidth = track.firstChild?.offsetWidth / 2;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search