4

I am trying to make a Nav in reactjs with Mobx State Tree.

Right now I have skinny vertical Nav bar with a list of icons. Now what I want to do is add sub menu items to certain ones. When these ones are clicked the Nav goes from skinny to wide(ie expands) and the sub menu items are shown. Once a user clicks on one of them the Nav goes back to skinny version.

What I think I need is a way that when an icon is clicked in my parent store a flag gets set to say "expand" but I don't know how to set that when a child gets clicked.

import { types } from "mobx-state-tree";
import NavItem from "./NavItem.js";
const NavStore = types
  .model("NavStore", {
    expanded: false,
    nav_items: types.array(NavItem)
  })
  .actions(self => ({}))
  .views(self => ({}))
  .create({

  });

export default NavStore;


import { types } from "mobx-state-tree";

const NavItem = types
  .model("NavItem", {
     expands: false,
     title: types.string
  })
  .actions(self => ({
    itemClicked() {

    }
  }))
  .views(self => ({}));

export default NavItem
chobo2
  • 75,304
  • 170
  • 472
  • 780

1 Answers1

6

You need to import getParent and (optionaly) hasParent functions:

import { types, getParent, hasParent } from ‘mobx-state-tree’

Then in your action call parent’s action:

if (hasParent(self)) {
  getParent(self).someAction(someParams);
}
Petr Lazarev
  • 2,604
  • 18
  • 17
  • I seen people do getParent(self, #). What is the difference vs something like getParent(self, 1) – chobo2 Jun 07 '18 at 16:15
  • Second parameter - depth (default is 1). So you can write getParent(self, 2) to get parent of the parent. I think there is no reason to write # for the depth, because it should be a number. – Petr Lazarev Jun 08 '18 at 09:16
  • I've check source code (https://github.com/mobxjs/mobx-state-tree/blob/master/packages/mobx-state-tree/src/core/mst-operations.ts) and seems getParent should raise an exception if second argument is not a number. – Petr Lazarev Jun 08 '18 at 09:27