How can I reset the viewport of my React-Flow project to fitView, without clicking the Controls fitView?

3.5k Views Asked by At

I'm working on a React-Flow project. I'm changing the layout of the nodes and edges with a button and I want the last thing to happen to be resetting the viewport to be centered (so just fitView).

How can I do this?

I've tried calling fitView() again but this doesn't seem to work at all.

3

There are 3 best solutions below

0
On

I have seen this pattern on the official documentation

window.requestAnimationFrame(() => fitView());
0
On

Try calling fitView inside of a setTimeout

setTimeout(reactFlowInstance.setView)

There is no need to pass a specific delay to the timeout, since (quoting the docs):

If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.

Which in our case is following the re-render of the Flow.

0
On

You can call fitView() on the react flow instance.

The instance you get from the onInit callback and save in a state, e.g. like this:

<ReactFlow ... onInit={(instance) => setReactFlowInstance(instance)} />