Reputation: 42644
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.
Upvotes: 31
Views: 27557
Reputation: 1806
const Example = inject(
'YOUR_STORE1',
'YOUR_STORE2'
)(
observer(({ YOUR_STORE1, YOUR_STORE2, OTHER_PROPS }) => {
return (
// Your Design
)
})
)
export default Example
Upvotes: 2
Reputation: 4173
A variant of @Tholle answer :
const Example = inject("myStore")(observer(({myStore, otherProp}) => {
// ...
}));
Upvotes: 8
Reputation: 112917
inject
returns a function that you can use on a observer functional component:
var Example = inject("myStore")(observer((props) => {
// ...
}));
Upvotes: 62