How to inject mobx store into a stateless component
23,049
Solution 1
inject
returns a function that you can use on a observer functional component:
var Example = inject("myStore")(observer((props) => {
// ...
}));
Solution 2
A variant of @Tholle answer :
const Example = inject("myStore")(observer(({myStore, otherProp}) => {
// ...
}));
Related videos on Youtube
Author by
Joey Yi Zhao
Updated on July 09, 2022Comments
-
Joey Yi Zhao almost 2 years
I am using
mobx
andreact
in a web application and I want to find a way to passmobx
store state to a stateless component. Below is my current component source code:import React from 'react'; import Panel from './Panel'; import {inject, observer} from 'mobx-react'; @inject(allStores => ({ form: allStores.store.form, })) @observer export default class Creator extends React.Component { connect() { console.log(this.props.form); }; render() { return ( <Panel form={this.props.form} connect={this.connect.bind(this)}/> ); } };
How can I change it to be stateless? I tried below code but didn't work:
const Creator = ({form}) => { const connect = ()=>{ console.log('xxxx,', form); } return ( <Panel form={form} connect={connect}/> ); } export default observer(Creator);
when I run above code, I got
undefined
value forform
on theconnect
method. How can I inject the store into stateless component? I tried to use@inject
on top of stateless component, but got a syntax error. -
Jason G over 3 yearssays it's not a function when you try to use it
-
PatS over 3 yearsIs
"myStore"
actually an instance the store you want to inject? I'm guessing it is. And where does inject come from? Is it mobx or mobx-react-lite? When I search for it I get a page mobx-react.js.org/recipes-inject that says this site is DEPRECATED. What version of MobX does this answer apply to? -
Tholle over 3 years@PatS You can inject any value, but most likely you will be injecting an instance of a store, yes. It's part of the mobx-react package. The documentation says "usually there is no need anymore to use
Provider
/inject
in new code bases; most of its features are now covered byReact.createContext
."