Image zoom with mouse wheel in React

So I’m trying to remake this version (taken and modified from this post) of an image zoom using the mouse wheel in React.

The thing is, even with the same maths and logic in React, it doesn’t perfectly work and I have no idea why. It seems like the image doesn’t zoom where the cursor is.

Here’s my component:

import React, { useState } from "react";

export default () => {
  const [pos, setPos] = useState({ x: 0, y: 0, scale: 1 });

  const onScroll = (e) => {
    const delta = e.deltaY * -0.01;
    const newScale = pos.scale + delta;

    const ratio = 1 - newScale / pos.scale;

    setPos({
      scale: newScale,
      x: pos.x + (e.clientX - pos.x) * ratio,
      y: pos.y + (e.clientY - pos.y) * ratio,
    });
  };

  return (
    <div onWheelCapture={onScroll}>
      <img
        src="https://source.unsplash.com/random/300x300?sky"
        style={{
          transformOrigin: "0 0",
          transform: `scale(${pos.scale}) translate(${pos.x}px, ${pos.y}px)`,
        }}
      />
    </div>
  );
};

I made a CodeSandbox: https://codesandbox.io/s/lingering-breeze-ho4do?file=/src/App.js

Try to zoom while your cursor is around the bottom right of the image, you’ll see the issue.

Answer

Sorry, read your question a bit more closely. The issue is transform order matters. You need to swap around scale and transform (https://codesandbox.io/s/wonderful-cerf-69doe?file=/src/App.js). Good luck with your project 🙂.