Home > Enterprise >  'slider' is possibly 'null'
'slider' is possibly 'null'

Time:12-27

I have no clue how to fix it, I am pretty sure it's something easy but I can't figure it out..

here's the line of code that is generating the error from TS:

    const slideLeft = () => {
      const slider = document.getElementById("slider");
      slider.scrollLeft = slider.scrollLeft - 1000;
  };

  const slideRight = () => {
    const slider = document.getElementById("slider");
    slider.scrollLeft = slider.scrollLeft   1000;
  };

The ID slider is causing the error ('slider' is possibly 'null')

      <div
        id="slider"
        className="flex items-center w-full h-full overflow-x-scroll scroll whitespace-nowrap scroll-smooth scrollbar-hide"
      >

Any pointers or tips is appreciated! Thanks!

CodePudding user response:

It is because the value returned from getElementById is either an Element or null if no element matching the specified ID was found.

There are a couple of optoins you can use to mitigate a null value.

Perform an explicit null check.

const slideLeft = () => {
    const slider = document.getElementById("slider");
    if (slider == null) return;
    slider.scrollLeft = slider.scrollLeft - 1000;
};

Use the non-null and non-undefined assertion operator.

const slideRight = () => {
    const slider = document.getElementById("slider");
    slider!.scrollLeft = slider!.scrollLeft   1000;
};

CodePudding user response:

The document.getElementById method has a return type of HTMLElement | null. If no element with the provided id exists in the DOM, the method returns a null value.

To solve your problem, just check if slider contains a value:

const slideLeft = () => {
  const slider = document.getElementById("slider");

  if(slider) {
    slider!.scrollLeft = slider!.scrollLeft - 1000;
  }
};
  • Related