Search code examples
reactjsnext.jszooming

Get transform context


I have Nextjs app and I use react-zoom-pan-pinch for transformation one of containers.

<TransformWrapper
   limitToBounds={false}
   centerZoomedOut={true}
   minScale={0.5}
   maxScale={2}
   panning={{ excluded: ['input'] }}
   doubleClick={{disabled: true}}
 >
   {({zoomIn, zoomOut, setTransform, resetTransform, ...rest}) => {

    actionReset = resetTransform;
    increaseZoom = zoomIn;
    decreaseZoom = zoomOut;
    setScale = setTransform;

    const context = useTransformContext();
    console.log(context)

    return (
      <TransformComponent wrapperClass="project-global-canvas-area">
        ...
      </TransformComponent>
    );
  }}
</TransformWrapper>

I have 2 problems:

  1. I need to have access to state of transform context, I use the useTransformContext hook, but I got the error:

Server Error Error: Transform context mus be placed inside TransformWrapper

Where I can place this hook for getting the state?

  1. I need state custom zoom value outside the transform component. There are no problem with zoomIn() and zoomOut(), but I have problem with setTransform().

I try call it:

setScale(100, 100, 1.5)

but nothing change with the error in console:

Detected NaN set state values


Solution

  • Not sure about your second problem, but the first one happens because the children in TransformWrapper is a render prop. When you use hooks inside render props, they are being called from the parent component. In your case parent component is TransformWrapper and useTransformContext should be called from child component. Using render prop there TransformWrapper is the one that calls useTransformContext. You have to make new component that uses all that logic from render prop

     <TransformWrapper
       limitToBounds={false}
       centerZoomedOut={true}
       minScale={0.5}
       maxScale={2}
       panning={{ excluded: ['input'] }}
       doubleClick={{disabled: true}}
     >
       {(params) => <Comp {...params} />}
    </TransformWrapper>
    
    const Comp = ({zoomIn, zoomOut, setTransform, resetTransform, ...rest}) => {
      
        actionReset = resetTransform;
        increaseZoom = zoomIn;
        decreaseZoom = zoomOut;
        setScale = setTransform;
    
        const context = useTransformContext();   // here you will get the value
        console.log(context)
    
        return (
          <TransformComponent wrapperClass="project-global-canvas-area">
            ...
          </TransformComponent>
        );
    }