Routing in React

Routing is the ability to navigate through different parts of the application through a URL or by performing an action on the elements within the application. Routing in React is similar to this. In this article we will look at one of the libraries in React that will allow us to navigate through pages which is React-Router.

What is React Router?

React Router is a standard library in React that is used for navigating through different pages, keeping the UI and URL in sync and simplifying user experience. It is mostly used in Single Page Applications (SPA). SPA's mostly have multiple pages/views which are rendered without loading the whole page when we click on a component after checking its route.

React Router Library

The library contains three different npm package variants:

=> react-router - the core library
=> react-router-dom - variant of the core library used for web development
=> react-router-native - variant of the the core library used for mobile app development

The core library does not need to be installed explicitly, but the other two depending on the requirement needs to be installed and they import all the functionalities of the core library.

npm install --save react-router-dom

React Router Components

Basically there are three key components that are widely used in the react router library. We will have a look at each of them:

Routers

A Router is a parent component that is used to store other components in it and is the core of every application using this library.

BrowserRouter is one of the routers that is available in the library. It is a good fit for web applications and is used precisely for applications which have a dynamic server and knows how to handle any type of URL

HashRouter is another router available for web development which is used for static servers and handles URL it knows of, if the server does not know about the path it wont respond to it.

ReactDOM.render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>,
  document.getElementById(‘root’));

History

The router we use creates a history object that keeps the track of the pages we visit and re-renders the page on every URL change. The history object created contains a number of properties and one of which is location whose value is an object which is derived from the URL. The location object looks like

{pathname, search, state ,hash }

Route Matchers

Route matchers are components which match the path and URL and render UI depending on the same. There are 2 route matching components available:

Route

It is one of the most important components of the library. It renders UI when the the URL matches the route's path. The path is a prop of Route component which holds the pathname that should be matched with the current URL.

<Route path='/home'/>

All paths that start with home in the above example are matched, suppose if there is another path as '/home/2' or 'homePage' it would still be a match. To overcome this ambiguity there is another prop called as exact. It ensures that when the pathname and the current URL are an exact match then only the corresponding UI will be rendered.

<Route exact path='/home'/>

We need to specify which component to render upon a match which is done by the component prop.

<Route exact path='/home' component={Home}/>

In case if we want to pass an extra props to the element, there is an option of inline rendering with the render prop. It excepts a function and returns an element when the path matches to that of URL.

<Route exact 
  path='/home' 
  component={Home} 
  render={()=>(<div>Home Page</div>}/>

In case we want to render some element irrespective of whether the path matches the URL, we have a prop called children which will render in every scenario.

<Route children = {props => <div> Welcome to my Page</div>} />

Switch

The library contains a Switch component which wraps multiple Route components in it and picks the first URL and path match and ignores the rest of the Route components.

<Switch>
  <Route 
    path=”/home” 
    render={() => (<div>Home Page</div>)}
  />
  <Route 
    path=”/home/2" 
    render={() => (<div>Home Page 2</div>)}
  />
</Switch>

In the above example if the URL is '/home/2', only Home Page will be rendered, as Switch component matches the path of the first Route and URL.

Navigation or Route changers are components which are used to redirect to some other page or show some other components on its click. The react router library has basically 3 Navigation components:

Link

It is used to navigate to different pages of application, it is similar to anchor tag the only difference being that while using the Link component the page does not reload like anchor tag but just changes the UI. It is to note that the URL will change when we click on the Link component.

<Link to ='/home'> Home </Link>

The Link component has a prop called to which is the location where the user will be redirected to.

NavLink

NavLink is similar to Link the only thing that NavLink has an extra prop called activeClassName which is used for styling purpose. When the URL matches the pathname of the component the class mentioned in the activeClassName prop is applied to the Link.

<NavLink to="/home">Home</NavLink>

Redirect

The redirect component is used to forcefully send the user to some other page. Considering the scenario when you want to check if the user is authenticated and if not authenticated we will have to forcefully send the user to Login page.

<Redirect to="/login" />

Conclusion

The purpose of this article was to help you understand what is routing and how it can be implemented in React with minimal efforts. React enables us to develop Single Page Applications which give the user better experience in browsing by minimizing unnecessary page reloads and to achieve this Routing plays an important role.

I hope the concepts of Routing and why this library is so important were clearly communicated by me and it helped expand your knowledge on the same.

Thanks for Reading. Happy Learning!