Store observer and reactions

Polotno has rich store API that you can use to observe and control canvas content. store object is created using mobx library. You can use mobx js methods to create react components.

Observable component

To create a component that is automatically updated, when canvas is changed you need to use observer api from mobx-react-lite library:

import { observer } from 'mobx-react-lite';
import { createStore } from 'polotno/model/store';

const store = createStore({
  key: 'YOUR_API_KEY', // you can create it here: https://polotno.com/cabinet/
})

// this react component is wrapped into observer
// it will be automatically updated, when number of elements on active pages is changed
const App = observer(() => {
  return (
    <div>
      <p>Elements on the current page: {store.activePage?.children.length}</p>
    </div>
  );
});

Store reaction

store object has a "change" event to listen to when some content on canvas is changed. The event triggered only when canvas content is changed. If you select or deselect elements, it will NOT trigger "change" event.

store.on('change', () => {
  console.log('something is changed');
});

In some cases, you may want to react to selection or some other data change in the store. In the case you can use reaction or autorun methods from mobx library:

import { reaction } from 'mobx';

reaction(() => {
  const firstElement = store.selectedElements[0];
  const isTextSelected = firstElement?.type === 'text';
  return isTextSelected
}, (isTextSelected) => {
  // here we can do something when text is selected
  console.log('text is selected', isTextSelected);
})

News, updates and promos – be the first to get 'em

News, updates and promos – be the first to get 'em