Ido Barash
Ido Barash

Reputation: 5122

React + mobx + openlayers 3

I have a map app using react.

It has 3 components:

  1. sidebar - contains buttons that will execute map function such as zoom in.
  2. map-wrapper - contains the openlayers map.
  3. View that renders them both.

View:

 export default class MapView extends Component {

  render() {
    return (
      <div>
          <Sidebar />
          <MapWrapper />
      </div>
    );
  }

Sidebar:

 export default class Sidebar extends Component {
  render() {
    return (

      <div>
          <ul>
            <li>MAPS</li>
            <li onClick=zoomIn> Zoom In + </li>
            <li onClick=zoomOut> Zoom Out - </li>
          </ul>
      </div>

    );
  }
}

Map is just this: https://github.com/pka/ol3-react-example

Now I'd like to implement the following logic: press on the zoom will zoom in the map.

How can I do this using mobx?

What will the store hold? What is the observer and what is the observable?

Regards, Ido

Upvotes: 1

Views: 363

Answers (1)

Mouad Debbar
Mouad Debbar

Reputation: 3226

I would do something like this:

// The store:
class MapStore {
  @observable zoom = 4;
}

const store = new MapStore();

// The component:
export default function Sidebar(props) {
  return (
    <div>
      <ul>
        <li>MAPS</li>
        <li onClick={zoomIn}> Zoom In + </li>
        <li onClick={zoomOut}> Zoom Out - </li>
      </ul>
    </div>
  );
}

// The click handlers
function zoomIn() {
  store.zoom++;
}

function zoomOut() {
  store.zoom--;
}

// The observer
// See docs: https://mobxjs.github.io/mobx/refguide/reaction.html
mobx.reaction(
  () => store.zoom,
  (zoom) => {
    map.getView().setZoom(zoom);
  }
);

Some things that I didn't cover:

  • Where to get the map instance from.
  • Handle min/max values for zoom.

Upvotes: 2

Related Questions