Programmatically changing Node dimensions in React Flow
-
Changing a node’s dimensions sounds simple. But doing it consistently in React Flow isn’t so straightforward.
When you look at the
Nodetype, you’ll noticewidthandheightattributes. It might seem like you can just update those. But according to the React Flow docs, those values are read-only. The same goes formeasured: { width: number; height: number }.So how do you actually change a node’s dimensions?
The React Flow team recommends using CSS. From the docs:
“You shouldn’t try to set the width or height of a node directly. It is calculated internally by React Flow and used when rendering the node in the viewport. To control a node’s size you should use the style or className props to apply CSS styles instead.”
That usually works. But there’s a catch.
If you want a consistent way to both set and get a node’s dimensions, relying on the
styleprop might not be enough. Why? Because of theNodeResizercomponent.NodeResizerlets users resize nodes manually using UI handles. But when they do, React Flow doesn't update thestyleprop. Instead, it directly modifies thewidthandheightattributes using internal state changes.If you look at how
NodeResizerworks under the hood, you’ll see that React Flow uses aNodeDimensionChangeto update the node’s size.So how can you trigger that same kind of change programmatically using only official React Flow methods?
Use
applyNodeChangesfrom the React Flow API:const customDimensionsChange: NodeDimensionChange = { id: 'node-1', type: 'dimensions', dimensions: { width: 300, height: 200 }, setAttributes: true, }; setNodes((nodes) => applyNodeChanges([customDimensionsChange], nodes));This updates the
widthandheightattributes properly. It’s the most consistent way to change node dimensions programatically in React Flow.