React Router is a JS library available through NPM that helps mainly with 2 problems:
Stop reading if you are not building entire applications using React – you don’t need React-Router for single page applications or small components.
For the rest of us building real web applications, we need to connect several views (React components) into one big application. That process is called "routing."
For example, we need the following application URLs to match the following components:
What pages/views do you want your app to have? You can always start with the basic ones:
The rest of the pages depend on your application and on how you want your users to navigate through your site.
This is the sitemap for any typical e-commerce website:
Once you have finished mapping your application views with URLs, you can start coding everything and that is when React-Router comes in!
The best practice is always creating one component called
<Layout /> which will take care of routing the users to the specific views they should see, depending on each of the particular URLs.
This is an example of the same e-commerce sitemap but now using React Router v4:
There are 3 components to understand here:
<Route>that matches the URL will be displayed.
This route is telling React that when the URL matches "sign-up", the component Signup should be displayed.
<a>are now a Problem
Anchors take users to other websites or URLs – and that is amazing for simple plain HTML+JS – but, now we DON’T want our users to be taken to other websites or URLs. We want them to remain in the same tab but be able to load the next page without having to refresh. We have two possible approaches of doing that:
React Router created a component that we can use instead of
React Router always passes to each view a prop called "history" which contains a lot of useful information to use when routing users. One of its many useful utilities is the "push" function that basically redirects the user to a given path.
Here is a live example using everything that we’ve learned in this reading. Please click and play to understand it, learn it and replicate it: