mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 350 forks source link

Combine Stateless Components and Class Components #817

Closed lapidus closed 4 years ago

lapidus commented 4 years ago

I have a working setup for Stateless components:

// State
export const useMyAppStore = () => {
  return useContext(StoreContext)
}

// In the Component
const App = observer(() => {
  const store = useMyAppStore()
})

But I have one "Map Class component" that requires inner state. How can I inject the same Store into a class component and make it observe the state? I tried the below but it doesn't quite work:


import { useMyAppStore } from "./state"

@inject(useMyAppStore)
@observer

class Map extends Component {
  constructor(props) {
    super()
        console.log(props)
    }
}

Thanks!

danielkcz commented 4 years ago

But I have one "Map Class component" that requires inner state.

What does that even mean? Do you know about useState? :)

With your own Context, you cannot use inject, but you can use contextType as easy escape hatch.

lapidus commented 4 years ago

Thank you. I am closing for now as it was perhaps not the best explanation. And I have a functional workaround :)

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs or questions.