A React hook that synchronizes scrolling across multiple elements. Useful for side-by-side comparisons, split views, or any scenario where synchronized scrolling enhances user experience.
- Synchronizes vertical and horizontal scrolling.
- Supports proportional scrolling (elements scroll proportionally to their content size).
- Lightweight and easy to use.
- Written in TypeScript.
Using pnpm:
pnpm add @n0n3br/react-use-scroll-syncUsing npm:
npm install @n0n3br/react-use-scroll-syncUsing yarn:
yarn add @n0n3br/react-use-scroll-syncimportReact,{useRef}from"react";import{useScrollSync}from"@n0n3br/react-use-scroll-sync";constMyComponent=()=>{constref1=useRef<HTMLDivElement>(null);constref2=useRef<HTMLDivElement>(null);constref3=useRef<HTMLTextAreaElement>(null);// Synchronize scrolling for ref1, ref2, and ref3useScrollSync([ref1,ref2,ref3]);// With options// useScrollSync([ref1, ref2], { horizontal: true, vertical: true, proportional: false });return(<divstyle={{display: "flex"}}><divref={ref1}style={{width: "200px",height: "200px",overflow: "auto",border: "1px solid black",marginRight: "10px",}}>{/* Long content here */}{[...Array(50)].map((_,i)=>(<divkey={i}>Item {i+1} in Pane 1</div>))}</div><divref={ref2}style={{width: "300px",height: "200px",overflow: "auto",border: "1px solid black",}}>{/* Different long content here */}{[...Array(30)].map((_,i)=>(<divkey={i}style={{height: "30px"}}>
Item {i+1} in Pane 2
</div>))}</div><textarearef={ref3}style={{width: "200px",height: "200px",overflow: "auto",border: "1px solid black",marginLeft: "10px",}}>{[...Array(100)].map((_,i)=>`Line ${i+1} in Textarea\n`).join("")}</textarea></div>);};exportdefaultMyComponent;refs:React.RefObject<HTMLElement | null>[]An array of React refs pointing to the DOM elements whose scrolling should be synchronized.options(optional):objecthorizontal(optional):boolean- Enable horizontal scroll synchronization. Defaults totrue.vertical(optional):boolean- Enable vertical scroll synchronization. Defaults totrue.proportional(optional):boolean- Enable proportional scroll synchronization. Whentrue, elements will scroll proportionally to theirscrollWidth/scrollHeightrelative to theirclientWidth/clientHeight. Whenfalse, they scroll pixel by pixel. Defaults totrue.
{ triggerSync: () => void }: An object containing atriggerSyncfunction.triggerSync: A function that can be called to manually re-synchronize the scroll positions of the elements. This can be useful if content changes dynamically and affects scroll dimensions.
An example application demonstrating the usage of react-use-scroll-sync can be found in the example directory of this repository.
To run the example:
- Clone the repository.
- Navigate to the
exampledirectory. - Install dependencies:
pnpm install - Start the development server:
pnpm dev
Contributions are welcome! Please feel free to submit a pull request or open an issue.
MIT © rogeriolaa