At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

A Complete Guide For React Routing And Navigation

  • By Karthiga M
  • December 21, 2018
  • 2085 Views

When it comes to “Routing concepts”, React has its own powerful routing techniques. Initially, React does not have any built-in library for navigation but later the React Community has been kept introducing many router libraries. To be precise, “React router”, React router is the most interesting concept which has the navigation techniques and components that help us to set the declarative routes in our application that has the powerful navigation features. And, what we like in React is, it has the clear declarative routing so you don’t have to worry about creepy navigation issues every time. So let’s start with something interesting in React and will have a closer look on react routers today.

Installing react-router-dom

Basically, React-router has three packages,

  • React-router
  • React-router-dom
  • React-router-native

React-router package has core routing components and functionalities.
React-router-dom involves in routing components and its functionality API for web browser.
React-router-native involves in routing components and its functionality API for mobile.
Follow this command to install react-router-dom

npm install --save react-router-dom

 
 

Components Of React Routers:

There are 3 types of components in routers,

  1. Routers components
  2. Router Matching Components
  3. Navigation Components

 

Router Components

Basically, <BrowserRouter>, <HashRouter> used for web browser based projects so before using this, first, we should decide which type of router we are going to use in our project.
import { BrowserRouter as Router, Route, Link } from “react-router-dom”;

  • <BrowserRouter> – It should be used when you have the server that will handle & response to dynamic requests.
  • <HashRouter> – It should be used for the static websites which means the server can only respond to the files which its familiar with.

However, <BrowserRouter> remains as the preferable routers for developers due to its power in handling both static and dynamic requests. However, <HashRouter> and <BrowserRouter> both will create a specialized “history object” for our project.
In case if you’re not aware about the “History object” then here is the quick view,

History

Each router creates a history object known as History API which can hold and manage the current location and previous locations via history.location. Also, it will re-render whenever the websites changes based on the history object.
The location property is an array of objects which will take the last element of an array as the current location of the site and we can also manipulate the array using history.push() or history.replace.
All the other components which are provided by the react router must be rendered because it will rely on the history object which will be available only through the context. Therefore, all the components delivered by React router must be rendered as descendants of a router component.

Router Matching Components

Here are the two route matching components <Route> and <Switch>,

1. <Route>

<Route> components have the prop called ‘path’, when this prop matches with the current location’s path name then it will fetch the particualr component location and will serve the page of that component.
On other cases, when <Route> matches with the location then it will render its content and if it doesn’t get a match then it will return NULL. Also, you can include <Route> anywhere in your project if you like to render the content based on its location.

Path

A <Route> should accept the path prop, A path prop is a string which will match with the pathname of the current location’s to render the appropriate React element. By chance, if the path doesn’t match with any of the defined locations then the route will not render anything.

Matching Paths

React Router uses the path-to-regexp package to determine whether the route element’s “path prop” matching the current location or not. It will concert the path string into a regular expression, which will be matched with the location’s pathname so when the route’s path matches, a destined object will be created with the following properties:

  • URL – the matched part of the current location’s pathname
  • Path – the route’s path
  • isExact – It is a boolean value , It matches path === pathname
  • Params – an object containing values from the pathname that were captured by path-to-regexp

Function RouterExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home Page</Link>
</li>
<li>
<Link to="/index_page">Listings</Link>
</li>
<li>
<Link to="/listing">Topic Listing</Link>
</li>
</ul>
<hr />
<Route exact path="/" component={HomePage} />
<Route path="/index_page" component={Listings} />
<Route path="/listing" component={TopicListing} />
</div>
</Router>
);
}

 
 

2. <Switch>

The <Switch> component is not exactly used to make a group or not required to make a group of <Route>. But at the same time, <Switch> also will iterate over all <Route> element and will render the first element which will match with the current location. It will work and render like a first child to match the current location.

  • <Switch> has the two child <Route> or <Redirect> elements.
  • <Route> elements are matched based on their path prop and also <Redirect> elements are matched based on prop. Whereas the <Route> with no path prop or a <Redirect> with no prop will always match the current location.
  • When you try to include a <Redirect> in <Switch> then it can use any of the <Route>‘s location matching props: For example, path, exact, and strict are the alias for the path prop.
  • If a location prop is given to the <Switch>, it will override the location prop on the matching child element.

 

<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/index_page" component={Listings} />
<Route path="/listing" component={TopicListing} />
</Switch>

 
 

Related: Top 10 React Components Libraries Every Javascript Developers Must Know

 

<Redirect>

<Redirect> also navigating the new page. The new location overrides the current location in the history object. It has the object and two props called pathName and state.
pathName – PathName is the name of the route which will match with the current location.
State – State holds the current location of navigation.

<Route
     render={props =>
       wrongAuth.isAuthenticated ? (
         <Component />
       ) : (
         <Redirect
           to={{
             pathname: "/login",
             state: { from: props.location }
           }}
         />
       )
     }
   />

 
We’re done with exploring the core concepts of React router along with its benefits so now it’s your turn to choose your favorite method. Post us your preferable methods in the comment section. Learn more about React and other technologies from the largest blog portal.

Karthiga M

A desired and an ideal full stack developer having 2 years of experience in web development, Acquiring strong development skills in building Ruby On Rails and React Js applications.