Search code examples
collectionsreactjsreactjs-fluxflux

Using collections of data in a store with React and Flux


I have a React + Flux application that uses multiple tab-pages of data. Each tab-page displays the same kind of data (e.g. an invoice), but from another object. Based on other posts I read on this subject, I decided to create a collection in the 'InvoiceStore' that contains an 'Invoice' object for every tab page that displays an invoice.

On every tab (in the details of the invoice), there are multiple widget-like components. These components are nested in multiple layers.

The challenge is that every component should know for which invoice object the data must be displayed. I know that I can arrange that by passing data (actual data or the 'key' of the item in the invoices collection) from the top component of an invoice (tab) to each of its descendants, but that would imply that the components in the middle would need to pass the received properties to its children. This seems like overkill to me.

Is it possible to have some kind of variable that has a scope of one component and its descendants? Or is there another sort of 'standardized' solution for this challenge?

Suggestions are really appreciated!


Solution

  • You can pass through props with JSX spread attributes: {...this.props}, which are based on the ES7 spread operator proposal.

    This destructures all the props you received in the parent and passes them to the child. Occasionally, you don't want to pass all the props, and then you need to comb out (or add in) the props you want to pass explicitly. For that, it may be useful to use the new destructuring syntax available in ES6.

    Example:

    <MyChildComponent
      foo={bar}
      baz={qux}
      {...this.props}
    />
    

    There is also an undocumented, hacky technique using this.context, but that API is unstable and is likely to change. The spread operator is currently the technique recommended by the React team.