• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • GUEST POST
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)

Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)

By Sigit Prasetya Nugroho ∙ June 1, 2020 ∙ Javascript ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

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.

Related Articles :

  • Introduction And Everything That Must Be Known About ReactJS
  • Guide To Use Axios With React (Free Bonus Code)

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.

React Router Dom Tutorial For Beginners

Table of Contents

  • 1 Installing React Router
  • 2 React Router Dom Component
    • 2.1 Router components
    • 2.2 Route Component
    • 2.3 Switch Route
    • 2.4 Passing the url parameters
    • 2.5 Link Components
    • 2.6 Redirect component
  • 3 Protected Route react
    • 3.1 How to create a protected route in reactJS
  • 4 Conclusion

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:

The Different HashRouter And BrowserRouter React Router Dom

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.

React Route Without Exact

To overcome this, we can use the “exact” property as follows :

1
<Route exact path="/" component={HomeComponent} />

Using Exact And Switch In React Router
Learn more : https://reacttraining.com/react-router/web/api/Route/exact-bool

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

  1. <BrowserRouter> needs to be rendered at the root of your component hierarchy.
  2. Always use the route Switch component so that the react router can work like a charm.
  3. Always use the route exact path property on Route component to render identical URLs / match the route.
  4. React router hooks can only be used on function / stateless components. For stateful / Class components, you can use props.
  5. Don’t forget to use HOC withRouter to be able to use props match, location, history object.
  6. 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.

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • The Right Way Understanding React Lifecycle For Beginners
  • [Problem Solved] React Error: ENOSPC: System limit for number of file watchers reached

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com