Skip to content

Storing react refs in MST model #1717

Answered by EmilTholin
filipnathanel asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @filipnathanel!

Very interesting. You could e.g. store the ref in a volatile state variable.

Example (CodeSandbox)

import { types } from "mobx-state-tree";
import { observer } from "mobx-react-lite";
import { useEffect, useRef } from "react";

export const StageModel = types
  .model("Stage", {
    start: types.string,
    stop: types.string,
    isActive: false
  })
  .actions((stage) => {
    let ref;

    return {
      setRef(r) {
        ref = r;
      },
      setIsActive(isActive) {
        stage.isActive = isActive;

        if (ref) {
          ref.current.style.backgroundColor = isActive ? "green" : "red";
        }
      }
    };
  });

const stage = StageModel.create({
  start

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@filipnathanel
Comment options

@zavx0z
Comment options

Answer selected by EmilTholin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants