19

I am using mobx and react in a web application and I want to find a way to pass mobx 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 for form on the connect 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.

Joey Yi Zhao
  • 23,254
  • 37
  • 138
  • 276

2 Answers2

49

inject returns a function that you can use on a observer functional component:

var Example = inject("myStore")(observer((props) => {
  // ...
}));
Tholle
  • 83,208
  • 13
  • 152
  • 148
  • Is `"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 https://mobx-react.js.org/recipes-inject that says this site is DEPRECATED. What version of MobX does this answer apply to? – PatS Oct 20 '20 at 01:07
  • @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](https://github.com/mobxjs/mobx-react#provider-and-inject) 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 by `React.createContext`." – Tholle Oct 20 '20 at 07:15
4

A variant of @Tholle answer :

const Example = inject("myStore")(observer(({myStore, otherProp}) => {
  // ...
}));
Xero
  • 3,257
  • 3
  • 34
  • 57