reactjstypescriptintersection-observer

Why I take 'Expected 1 arguments, but got 2.' error of IntersectionObserver?


I converted a code (from https://react.dev/reference/react/useEffect#usage) to TypeScript like:

function Box() {
  const ref = useRef(null);

  React.useEffect(() => {
    const div = ref?.current;
    const observer = new IntersectionObserver(entries => {
      const entry = entries[0];
      if (entry.isIntersecting) {
        document.body.style.backgroundColor = 'black';
        document.body.style.color = 'white';
      } else {
        document.body.style.backgroundColor = 'white';
        document.body.style.color = 'black';
      }
    });
    observer.observe(div, {
      threshold: 1.0
    });
    return () => {
      observer.disconnect();
    }
  }, []);

  return (
    <div ref={ref} style={{
      margin: 20,
      height: 100,
      width: 100,
      border: '2px solid black',
      backgroundColor: 'blue'
    }} />
  );
}

And in the observer.observe(div, { threshold: 1.0 }); part I took an error:

Expected 1 arguments, but got 2.

I created TypeScript + React with npm create vite@latest and here is my package.json:

{
  "name": "react-tutorial",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.0.37",
    "@types/react-dom": "^18.0.11",
    "@typescript-eslint/eslint-plugin": "^5.59.0",
    "@typescript-eslint/parser": "^5.59.0",
    "@vitejs/plugin-react": "^4.0.0",
    "eslint": "^8.38.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.3.4",
    "typescript": "^5.0.2",
    "vite": "^4.3.9"
  }
}

Solution

  • You can pass options as the second argument of IntersectionObserver

    new IntersectionObserver(callback, options)

    const observer = new IntersectionObserver(entries => {
          const entry = entries[0];
          if (entry.isIntersecting) {
            document.body.style.backgroundColor = 'black';
            document.body.style.color = 'white';
          } else {
            document.body.style.backgroundColor = 'white';
            document.body.style.color = 'black';
          }
    }, {
      threshold: 1.0
    });
    
    observer.observe(div)