react-router provides great route handling with route params and query params. Flux provides a pattern for building React apps, including a pattern from providing data to your components. Here’s a straightforward way to make route changes trigger data changes in your components.
Note: Code here reflects usage of react-router 0.11.x.
It is often the case that we’ll need to trigger data changes in a react component in our Flux app because of a route transition. A prime example of this would be on an object show page, where the details of a particular object are being shown. In our example, let’s say that we’re showing the details of a book, such as title, author, and description.
The route to our book detail page is likely defined as:
The handler is just a controller-component that defines the view. It might look simply like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
Note that the view component references a
BooksStore for getting its initial state. The state of
book will also be updated as the
BooksStore emits that its data has changed and
this._onChange is called.
Every time a route transitions, react-router has a
Router.run callback that will also run in order to render the matching route. This will also be a great place to put our action to signal to our Flux app that routes are transitioning and therefore other stuff like data in the display might need to change as well.
1 2 3 4
Important note: Make sure the transition action is called after
React.render so that the change emission will be detected after render, otherwise you’ll be one route transition behind.
BooksAction.transition definition is something very simple – something that can trigger events on the dispatcher:
1 2 3 4 5
The final connection is in the store, where the dispatched action can be listened for an then trigger the store event, updating the component views:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
At this point, all the route transitions should trigger data changes in views. Visiting the url
/books/1 and then the url
/books/2 should display different data on screen according to which book id was in the route.
Router.Link should work correctly, usable instead of buttons with actions being triggered on click.
react-router and Flux make for a great combo in this way, right? What adjustments would you make?