Almost every modern framework has a route feature (specifically React app). In the modern Web, a router is a module whose job is to manage the path/route in web-based applications.
Routers manage the entrances in the form of requests to applications; they sort and process URL requests for later processing according to the URL’s final destination.
React router used for moving between web pages without reloading the browser tab. On a modern website, React router is the main component for creating web applications with SPA concepts.
SPA allows us to move web pages without re-downloading assets from the server, such as Javascript and CSS files. React has a well-known router module such as React-router-dom, which provides many features that we will discuss in this article.
At the time this article was written, I used the latest react-router-dom module version 5.2.0 or often called react router 5. let’s begin the tutorial.
There are 2 types of react-router modules, namely:
- react-router-dom used for web (ReactJS)
- react-router-native used in mobile apps (React native)
In this tutorial, we only focus on react-router-dom because this article focuses on Reactjs tutorial.
Table of Contents
Installing React Router
To install react-router-dom, it’s easy enough, type the following NPM install command.
npm install react-router-dom
After a successful installation, you can use router components to manage the path of the react app. Some react-router components that are most often used to create website page flow include:
React Router Dom Component
Router components
Basically, react-router-dom has 2 types of routers used, namely <HashRouter> and <BrowserRouter> Both have their advantages depending on what type of Web we are building.
- <HashRouter> uses the hash (#) in the URL to create a component. is used to build a website for one static page.
- <BrowserRouter> uses the HTML5 history API to create components. history can be modified via pushState and replaceState.
For Example, if we create a static web or there is no server to render dynamic data, we should use HashRouter. Conversely, if we create a web that uses dynamic data with a backend server, then using BrowserRouter is the right choice.
My suggestion is to use the <BrowserRouter> because most of the applications you create are dynamic. As written on the official site of reacttraining.com:
It should be noted:
To use a router (<BrowserRouter>), make sure it’s rendered at the root of your element hierarchy. Source: https://reacttraining.com/react-router/web/guides/primary-components
In this article, we use <BrowserRouter> because the next tutorial we process data from the server.
Use like the following example:
1 2 3 4 5 6 7 | <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route path="/user" component={User} /> <Route path="/item" component={Item} /> </Switch> </BrowserRouter> |
Route Component
To implementing the React route, react-router-dom has provided the Route component with the path and component properties.
As an basic routing example
1 | <Route path = "/ new-destination" component = {ChoosenComponent} /> |
Explanation:
- path used as a URL path. (Routes without a path always match.)
- component: The name of the rendered component. The react component will be rendered when the location matches.
Another example :
If we have many routes, which component will be rendered first?
1 2 3 | <Route path="/" component={HomeComponent} /> <Route path="/user" component={UserComponent} /> <Route path="/item" component={ItemComponent} /> |
If we go to “/user” or “/item” , then the HomeComponent still be visible. It is because the “/user” and “/item” still included in the “/” pattern, so all URLs that have the “/” pattern will render the HomeComponent.
To overcome this, we can use the “exact” property as follows :
1 | <Route exact path="/" component={HomeComponent} /> |
By using “exact” props, HomeComponent only appears if our URL is in the path “/” with the same URL.
So, what if the pattern of the URL is a parameter? If we have two routes like the following Example
1 2 | <Route exact path=”/user” component={UserComponent} /> <Route path=”/user/:id” component={UserComponent} /> |
The Route above is nested routing. We can make both routes into a group using the Switch component.
Switch Route
If the application has many routes, it must be wrapped in <Switch>
If you don’t use the Switch route, usually React will display an error message like the following message:
Uncaught Error: A may have only one child element
Example
1 2 3 4 5 6 7 8 | <Switch> <Route exact path={path}> <h3>ItemPage</h3> </Route> <Route path={`${path}/:name`}> <ItemDetail /> </Route> </Switch> |
The Switch will check the pattern that matches the path of the Route and will only display 1 of the two components. So when the Switch finds a matching path, the Switch will ignore the other paths.
Exact and Switch are confused if you don’t try it directly.
So please use <Switch> instead of to better application.
Passing the url parameters
1 2 3 4 5 6 7 8 | <Switch> <Route exact path={path}> <h3>User Page</h3> </Route> <Route path={`${path}/:id`}> <UserDetail /> </Route> </Switch> |
To get the value :id from the Route above, the id value can be accessed as a string using useParams() hooks or through props. The different is :
useParams() hooks can only be used on stateless components. As for React’s Class / stateful components, please using props. See the following code:
1 2 3 4 5 6 | import React from "react"; import { useParams } from "react-router-dom"; export default (UserDetail = () => { let { id } = useParams(); return <h3>User Detail for Id : {id}</h3>; }); |
1 2 3 4 5 6 7 8 9 10 11 12 | import React from "react"; import { withRouter } from "react-router-dom"; class ItemDetail extends React.Component { constructor(props) { super(props); } render() { return <h3>Item id name : {this.props.match.params.name}</h3>; } } export default withRouter(ItemDetail); |
Important Note!
To use props.match.params, the component must be wrapped using HOC withRouter. Without HOC withRouter you can’t access the history object from props. What is HOC / High Order Component? Maybe I discuss in another article
Learn more withRouter HOC here.
Link Components
The route link used to move between pages. In the component, there is a property that always used like “to” . This property refers to the path on the Route to be headed.
Example:
1 | <Link to="/item">Item</Link> |
1 2 3 4 5 6 7 | <Link to={{ pathname: "/item", search: "?id=p0001", state: { itemShow: true } }} /> |
Redirect component
Redirects are used to redirect from a page to a new location. This component is almost similar to redirect on window.location.
<Redirect> is often used when checking a page’s permissions. The most common example is when creating a login page when a successful login user will be redirected to the main page.
Example of use
1 2 3 | if (this.state.islogout) { return <Redirect to="/login" />; } |
Here is my codesandbox :
The above components are most commonly used on ReactJS routers. There is one more method that is often sought by developers is how to protect routes on reactJS ?.
Protected Route react
React does not have a built-in component for creating protected routes, but you can do it quite easily.
If an application requires a private page / private route, protected routes play an essential role as the main door to ensure that users have access to a protected page.
Here’s how I make a private route that I have learned from various sources.
How to create a protected route in reactJS
1. Create new Jsx file as ProtectedRoute.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import React from "react"; import { Route, Redirect } from "react-router-dom"; const ProtectedRoute = ({ children, ...rest }) => { return ( <Route {...rest} render={({ location }) => localStorage.getItem("token") ? ( children ) : ( <Redirect to={{ pathname: "/login", state: { from: location } }} /> ) } /> ); }; export default ProtectedRoute; |
2. To using protected route, use the following code :
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 | import React from "react"; import "./styles.css"; import Login from "./Login"; import Dashboard from "./Dashboard"; import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom"; import ProtectedRoute from "./ProtectedRoute"; export default function App() { return ( <Router> <Switch> <Route path="/login"> <Login /> </Route> <ProtectedRoute path="/dashboard"> <Dashboard /> </ProtectedRoute> <Route exact path="/"> <Redirect exact from="/" to="dashboard" /> </Route> <Route path="*"> <Redirect exact from="/" to="dashboard" /> </Route> </Switch> </Router> ); } |
Examples of protected routes I will share in the article how to create a reactjs login page
Conclusion
- <BrowserRouter> needs to be rendered at the root of your component hierarchy.
- Always use the route Switch component so that the react router can work like a charm.
- Always use the route exact path property on Route component to render identical URLs / match the route.
- React router hooks can only be used on function / stateless components. For stateful / Class components, you can use props.
- Don’t forget to use HOC withRouter to be able to use props match, location, history object.
- Always use the protected Route to prevent unauthorized access.
The above react course is basic routing in React app. To learn more about the react router api, please read and read on the official react router site.
React-router version 5, makes a routing page very easy. Hopefully, the above article is easily to understood.
If your started with react, get a whole react course here.
Leave a Reply