Storing react refs in MST model #1717
-
Hey guys! There is that specific thing that I am trying to do: somehow Link React refs to MST Models I believe that this could be translated into more generic question: "Is it possible to store arbitrary data to MST models/stores ?" currently, I achieved this by storing the refs in React Context. but it doesn't make sense to maintain two sources of state, especially considering that this wouldn't be necessary in pure Mobx... The simplified code is something like below: Store
Model
React Parent Component
React Child Component
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @filipnathanel! Very interesting. You could e.g. store the 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: "yesterday",
stop: "tomorrow"
});
export default observer(function App() {
const ref = useRef(null);
useEffect(() => {
stage.setRef(ref);
return () => {
stage.setRef(undefined);
};
}, []);
return (
<button ref={ref} onClick={() => stage.setIsActive(!stage.isActive)}>
{stage.isActive ? "Active" : "Inactive"}
</button>
);
}); |
Beta Was this translation helpful? Give feedback.
Hi @filipnathanel!
Very interesting. You could e.g. store the
ref
in a volatile state variable.Example (CodeSandbox)