'Sync scroll react. div block with main scroll on window

I want to synchronize a divs scroll with a body scroll.

I tried some examples with two divs but I couldn't manage fix it with the body scroll.

Sample code with two divs: https://codesandbox.io/s/react-custom-scroll-sync-of-2-divs-10xpi

My Code

https://codesandbox.io/s/funny-rain-ditbv

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const firstDivRef = useRef();
  const secondDivRef = useRef();

  const handleScrollFirst = (scroll) => {
    secondDivRef.current.scrollTop = scroll.target.scrollTop;
  };

  const handleScrollSecond = (scroll) => {
    firstDivRef.current.scrollTop = scroll.target.scrollTop;
  };

  return (
    <div
      className="App"
      style={{
        display: "flex",
   
   
    
      }}
    >
      <div
        onScroll={handleScrollFirst}
        ref={firstDivRef}
        style={{
          height: "500px",
          overflow: "scroll",
          backgroundColor: "#FFDAB9",
          position: "sticky",
          top: "0px"
        }}
      >
        <div style={{ height: 5000, width: 300 }}>
          The first div (or it can be tbody of a table and etc.)
          {[...new Array(1000)].map((_, index) => {
            const isEven = index % 2 === 0;
            return (
              <div style={{ backgroundColor: isEven ? "#FFFFE0  " : "#FFDAB9" }}>
                {index}
              </div>
            );
          })}
        </div>
      </div>

      <div
        onScroll={handleScrollSecond}
        ref={secondDivRef}
        style={{
          height: "100%",

          backgroundColor: "#EEE8AA"
        }}
      >
        <div style={{ height: 5000, width: 200 }}>
          The second div
          {[...new Array(1000)].map((_, index) => {
            const isEven = index % 2 === 0;
            return (
              <div style={{ backgroundColor: isEven ? "#FFFFE0  " : "#FFDAB9" }}>
                {index}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}



Solution 1:[1]

Try the next example. This is a quick sketch but maybe it will help you.

https://codesandbox.io/s/gallant-goldwasser-19g4d?file=/src/App.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew F