'How can I bind zoom buttons to react d3 tree?

I’m trying to figure out how to bind zoom buttons to react d3 tree, however I haven’t found an approach that works while still maintaining the position.

The position resets every time I update the zoomLevel, meaning if I pan somewhere and adjust the zoomLevel, it jumps to the middle of the tree.

I want something like this https://jsfiddle.net/vbabenko/jcsqqu6j/9/

const TreeWrapper: FC<any> = ({ data }) => {
  const [zoomLevel, setZoomLevel] = useState(1);

  const scaleExtent = { min: 0.5, max: 3 };

  const zoomIn = () =>
    zoomLevel < scaleExtent.max &&
    setZoomLevel((prevLevel) => prevLevel + 0.25);

  const zoomOut = () =>
    zoomLevel > scaleExtent.min &&
    setZoomLevel((prevLevel) => prevLevel - 0.25);

  return (
    <Card title={null}>
      <button onClick={zoomIn} type="button">
        +
      </button>
      <button onClick={zoomOut} type="button">
        -
      </button>
      <Tree
        zoom={zoomLevel}
        scaleExtent={scaleExtent}
        translate={translate}
        zoom={zoomLevel}
        zoomable={true}
        initialDepth={1}
        collapsible={true}
        separation={{ siblings: 2, nonSiblings: 2 }}
        renderCustomNodeElement={(rd3tProps) =>
          renderForeignObjectNode({ ...rd3tProps, foreignObjectProps })
        }
        orientation="vertical"
        data={data}
      />
    </Card>
  );
};


Sources

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

Source: Stack Overflow

Solution Source