chobo2
chobo2

Reputation: 85785

How to Change Parent State from Child - Mobx State Tree?

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

Upvotes: 5

Views: 4039

Answers (1)

Petr Lazarev
Petr Lazarev

Reputation: 3182

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);
}

Upvotes: 7

Related Questions