Skip to content

Commit

Permalink
Use id instead of ref for scroller in Canvas
Browse files Browse the repository at this point in the history
Bug in react-scroll-sync where ref doesn't work
okonet/react-scroll-sync#79
  • Loading branch information
gina0605 committed Aug 7, 2023
1 parent a06304b commit e540ecc
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/components/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ export const Canvas = ({
onDelete,
}: CanvasProps) => {
const inputId = useId();
const scrollerId = useId();
const canvasRef = useRef<HTMLCanvasElement>(null);
const guideRef = useRef<HTMLCanvasElement>(null);
const scrollerRef = useRef<HTMLDivElement>(null);
const [prevZoom, setPrevZoom] = useState(1);
const [dotPos, setDotPos] = useState<number[] | null>(null);
const [selectable, setSelectable] = useState(defaultSelectable);
Expand All @@ -64,15 +64,15 @@ export const Canvas = ({
};

const getCenter = () => {
const scroller = scrollerRef.current;
const scroller = document.getElementById(scrollerId);
if (!scroller) return null;
const xCenter = (scroller.scrollLeft + scroller.clientWidth / 2) / prevZoom;
const yCenter = (scroller.scrollTop + scroller.clientHeight / 2) / prevZoom;
return [xCenter, yCenter];
};

const zoomScroll = (centerCoord: number[] | null) => {
const scroller = scrollerRef.current;
const scroller = document.getElementById(scrollerId);
if (!scroller || !centerCoord) return;
const [xCenter, yCenter] = centerCoord;
const xScroll = minmax(
Expand Down Expand Up @@ -165,7 +165,10 @@ export const Canvas = ({
useEffect(() => setDotPos(null), [data, target, selectable]);

useEffect(() => {
if (!data) scrollerRef.current?.scrollTo(0, 0);
if (!data) {
const scroller = document.getElementById(scrollerId);
if (scroller) scroller.scrollTo(0, 0);
}
}, [data]);

useEffect(() => {
Expand Down Expand Up @@ -270,7 +273,7 @@ export const Canvas = ({
</div>
<ScrollSyncPane>
<div
ref={scrollerRef}
id={scrollerId}
className="border-2 border-black w-full h-[90vw] md:h-[40vw] relative result-box overscroll-contain overflow-scroll"
>
{data === null && (
Expand Down

0 comments on commit e540ecc

Please sign in to comment.