React Router is the standard routing library for React. It keeps your UI in sync with the URL. This short article will give you some info how to quickly start using it. If you remember my React Countries app and React articles – we will use that app and add routing features to it, for the sake of practicing React Router library. You can find the source code here.
Where to start
- How Single-Page Applications (SPA) Work
- A Simple React Router v4 Tutorial
- Official React Router docs
- Google react router 4 😛
We have a few new things in the app:
- In the header you can see the current path
- About page
- If you click on the flag of some country it will take you to the country details page – example
First thing I did is to refactor the app a bit, so that it’s suitable for React Router. If you check index.js you will see that I wrapped everything with BrowserRouter (btw, documentation says that HashRouter should be used for static servers and BrowserRouter for dynamic serving, but seems that BrowserRouter also works without any problem with static AWS S3). Then App.js has been refactored to contain only the layout (header, main) and routing information. Depending on the path/url, main content will be different – ReactCountriesContainer, CountryDetails, About. Check those components for more details and React Router usage.
Another important thing is withRouter. If your component is not rendered using Route, but tries to access router params (match, location, history) – it will get undefined. In this case you have to wrap your components using withRouter HOC. You can see the example in App.js – const HeaderWithRouter = withRouter(Header). Also check redux integration.
This was ultra short article, but I hope it can help you to quickly start with React Router!