1
votes

I have a React component that I'm injecting some MobX values into. It contains a deeply-nested tree of children. Rather than injecting all the values that all the children need into the parent component, and passing them down through the whole tree, I also inject some data directly into individual child components.

This works fine, but what if I want two instances of this tree in my app, using different data? I can inject different data into the two instances of the top component, but how do I differentiate the child components that also need different data injected?

For example, if I use component A in two places, I can inject two different values for x into them. But if A contains component C as a descendant, how can I inject two different values for y into them (other than injecting them into each A and passing them down the tree)?

      ------ root --------
     /                    \
    A <-- inject foo.x     A <-- inject bar.x
   /                        \
  B                          B
 /                            \
C <-- inject foo.y             C <-- inject bar.y

I'm using the "Customizing inject" method of injecting, so my components take individual values rather than a single store.

const UserNameDisplayer = inject(
    stores => ({
        name: stores.userStore.name
    })
)(NameDisplayer)

Not sure whether that's the best way to do it though.

1
I don't I think I get the question, you can inject as many things with Provider into the tree as you want - mweststrate
@mweststrate Added the third paragraph and diagram. Hope that clarifies it. - JW.
Em no not really :) Are you sure you are not over-thinking this, why not just inject foo / bar? Or wrap C with a component that has a prop configuring what store it should pick? Or create different providers at the different A's? (Provider doesn't have to be at the root) - mweststrate

1 Answers

0
votes

What you want is impossible by logic.

You cannot specify what goes into C (foo.y) if you can't specify this on component A.

The whole idea of props is giving control to the higher component on values in subcomponent. This way Props is a contract of how the component A (including component C) can be used.

If you dont always want to use component A with component C you could only inject component C at root if you want it to as children:

<A/>
// or with C as child:
<A> 
  <C someProps={} />
</A>

this way component A wouldn't need to know about compoent C at all.

To keep coding simple and not a burden at some point you'd need to split your components in two:

  • Pure components that have props which it interacts with and some internal state if needed
  • And components that directly talk to Global state (mobx Store).

Trying to make EVERY component pure/abstract is simply overkill, these higher level components will still be too application specific to really re-use.