Routing
Learn how you can navigate among views of various components in a React Application.
We'll cover the following
React Router
Most single page applications will need some form of routing, meaning that we want to map certain functions or behaviors to a URL. For example, if we visit the URL of /users/manuel
, we would like to present the profile of the user manuel
.
React Router has established itself as the standard for routing in React single-page applications. Developed by Michael Jackson (yes, that’s his name!) and Ryan Florence (who has built over 10 different routers throughout the years), it boasts over 35,000 stars on GitHub, showing its popularity. It’s well maintained, has over 500 different contributors listed on GitHub, and integrates well with React principles due to its declarative nature.
Moreover, it can be used on the web (client-side and server-side) and in React Native. It’s a very universal, well-tested, and popular choice for routing.
React Router interface
The interface of React Router is relatively simple. In most of situations, you will only typically encounter five core components:
BrowserRouter
Link
Route
Redirect
Switch
We’ll learn about these components in detail later.
It offers an imperative History API, that can be extended via the history
package, which forms a thin layer over the native browser implementation, making it cross-browser compatible. It also provides a higher-order-component called withRouter
, which allows us to pass in routing relevant data from the Router
to another component.
React Router installation and usage
You can install React Router using the following:
npm install --save react-router-dom
Or, if you prefer using Yarn:
yarn add react-router-dom
React Router’s usage is declarative and can be achieved via the components mentioned above. Routers can be used anywhere in the application as long as the page tree itself is nested in a Router Context. In most cases, this context will wrap the entire application and exist only once:
Get hands-on with 1200+ tech skills courses.