projectstorm / react-diagrams

a super simple, no-nonsense diagramming library written in react that just works
https://projectstorm.cloud/react-diagrams
MIT License
8.58k stars 1.17k forks source link

What is a recommended way to re-render other React components based on changes in a diagram #786

Closed optimistiks closed 3 years ago

optimistiks commented 3 years ago

Let's say I have a sidebar with some buttons. When I click on a button, I do this

engine.getModel().addNode(node);
engine.repaintCanvas();

The node appears on the canvas, no issue here.

Now, I want to display a little checkmark next to the button, indicating that the node is present on the canvas. And I want to remove the checkmark when node is removed from the canvas. However, the sidebar is not re-rendered since adding the node is imperative, and nothing really changes. engine instance is not changed, getModel() return value is not changed. I thought about ways to solve it:

Or am I missing something? Is there some internal state which I can pull out into React component state to get the re-renders?

renato-bohler commented 3 years ago

Maybe you can listen to the entityRemoved event on the node and react to that. Something like:

node.registerListener({ entityRemoved: ({ entity }) => console.log('Removed entity', entity) });
engine.getModel().addNode(node);
engine.repaintCanvas();

You can then replace the console.log with some setState, a redux action dispatch or something like that.

optimistiks commented 3 years ago

Thanks! Could you confirm that re-creating an engine (with createEngine) on every render is a bad idea? Because I've seen it in some examples, but in other examples it's only created once.

renato-bohler commented 3 years ago

I'm not absolutely sure if this is really bad, but I would certainly avoid it.