App Academy: Week 7, Day 4
Over the last three days, we learned how to use React and Flux to build reactive views for web applications. Today, we dove deeper into React and learned how to use the React Router.
While single-page apps are definitely an improvement over multi-page apps as far as speed and reactivity to user interaction go, without the ability to dynamically change the URL while the user switches between views, our apps would miss out on a very important feature of single-page apps: apps that map URL routes to views, such as all multi-page apps, can have specific views linked to from other sites or applications and can be accessed directly by users typing the URL mapping to that view into their browsers.
The React Router allows us to maintain this functionality in our single-page apps and does so in a very intuitive manner not so different from the Rails Router. In the React Router, we list routes and tell the router which React component to map that route to. In addition, we can either nest routes within one another to create relative paths for the nested components or we can make top-level routes, whose paths are absolute.
One big difference between using React with the router and without it is in how we render nested components. Without the router, we simply include the nested component within the render method of the parent component. However, when one route is nested within another, the parent component is mapped to by a route that does not map to the nested component, and so it needs to be able to render itself both with and without that nested component. Thus, rather than including the nested component directly within the render method of the parent component, we include {this.props.chilren} within the parent component's render method. This works since the router automatically passes the components mapped to by any nested routes into the parent component's children prop whenever the nested route is accessed.
A different problem, though, is in how the components of nested routes receive props, since their parents can no longer pass props to them. The solution is to get whatever information such child components need from the route itself, via the this.props.params prop. For instance, if a FriendsIndex component needs to know which user's friends it should display, we can define our route to the index such that it will always have :userId somewhere in it. Then, our FriendsIndex can call an API to fetch that user's friends and set its own state accordingly so as to show all of her friends.
In addition to the above, we also learned how to do redirects within a single-page app using the history prop.
Overall, I found using the React Router to be very intuitive and to fit nicely into what we've learned about React so far.