React Router: everything you need to know

Share this Content

When building single-page applications, there are a number of factors you need to take into account when determining how you will handle routing. One popular option for routing in React is react-router. In this blog post, we will discuss everything about it.

React Router is a powerful routing library built on top of React that helps you add new pages, modify existing ones, and keep your application in sync with your URL. React Router is a declarative, component-based approach to routing. It uses the React component lifecycle to keep your UI in sync with the URL automatically.

Now before going to react-router, I’d like to introduce “Routing” to you.

What is Routing?

Routing is the process of selecting a path for traffic in a network, or between or among networks. Routing is performed for many kinds of networks, including telephone networks, electronic data networks, and road networks.

There are two primary functions of routing:

  1. Routing hides the complexity of the network from the users of the network
  2. Routing allows users to share the resources of the network

The first function, hiding the complexity of the network, is accomplished by using protocols. A protocol is a set of rules that govern the exchange of information between devices. Protocols define how devices will connect to each other, how they will identify each other, and how they will exchange information.

The second function, allowing users to share the resources of the network, is accomplished by using the concept of virtual circuits. A virtual circuit is a logical connection between two devices. Virtual circuits provide a way to multiplex the use of physical resources, such as bandwidth, among multiple users.

Routing can be classified into several different categories:

  1. Static routing: In static routing, the network administrator manually defines the route that traffic will take. Static routing is typically used in small networks.
  2. Dynamic routing: In dynamic routing, the route that traffic will take is determined by the network itself. Dynamic routing is typically used in large networks.
  3. Distance-vector routing: Distance-vector routing is a type of dynamic routing. In distance-vector routing, each router keeps a list of the distances to other routers. Distance-vector routing is typically used in small- to medium-sized networks.
  4. Link-state routing: Link-state routing is a type of dynamic routing. In link-state routing, each router keeps track of the state of the links to other routers. Link-state routing is typically used in large networks.

Types of Routing:

When we talk about types of routing, there are generally two types: client-side routing and server-side routing. Client-side routing is what’s used in Single Page Applications (SPAs). Server-side routing is used in traditional multi-page web applications. Let’s take a look at each type in more detail.

Client-side routing is the type of routing used in SPAs. When a user navigates to a different page in a SPA, the entire page doesn’t need to be reloaded from the server. Instead, only the necessary components are fetched and rendered to the client. This makes SPAs much faster and smoother for the user, as there is no need to wait for the entire page to load each time they navigate.

There are two popular libraries for client-side routing: React Router and Angular Router.

  1. React Router is the most popular library for routing in React applications. It is simple to use and has good documentation.
  2. Angular Router is the official routing library for Angular applications. It is more complex than React Router but can be used for more advanced features such as lazy loading.

Server-side routing is the type of routing used in traditional multi-page web applications. When a user navigates to a different page, the server needs to render the entire page from scratch. This makes server-side routing slower than client-side routing, as the server needs to do more work. However, it can be more convenient for developers as all the routes are defined on the server.

Routing is an important part of web applications. It allows you to define the flow of your application and make it easy for users to navigate. There are two main types of routing: client-side routing and server-side routing. Client-side routing is used in Single Page Applications (SPAs) and is faster and smoother for the user. Server-side routing is used in traditional multi-page web applications and is more convenient for developers.

Now, let’s talk about React Router.

What is React Router?

React-router is a routing library for React that is designed to help developers build single-page applications. It provides a number of features that make it easy to handle routing, including:

  • A simple API that is easy to use
  • Support for dynamic routing
  • Support for server-side rendering
  • A small footprint

React Router is a declarative, component-based approach to routing. It means that you can structure your code as you would structure your UI, and each route you define is a self-contained unit that can be passed around easily.

React Router uses a technique called dynamic routing, which allows you to build applications that are afraid of changes. In traditional web applications, the URL you see in the address bar is matched to a specific file on the server. React Router uses a different approach: it matches the URL to a component and renders that component into the DOM.

This has a few advantages:

  1. It makes it easy to write code that only runs when it needs to. For example, you can lazy-load components that are not immediately needed, which can improve your application’s performance.
  2. It makes it easy to share routes between different parts of your application. For example, you can have a /users route that is used by both the admin section of your site and the public site.
  3. It makes it easy to change the URL without having to reload the page. This is because React Router uses the browser’s history API to keep track of the current location.

React Router is available as a package on npm, and you can install it with the following command:

npm install react-router

Once you have React Router installed, you can import it into your application with the following line of code:

import { Router, Route, Link } from 'react-router';

The Router component is the root component of your application, and it is used to render the other components. The Route component is used to define a single route, and the Link component is used to navigate between routes.

To use React Router, you will need to create a file called ‘App.js‘ in the src directory of your project. The ‘App.js‘ file should look like this:

import React from 'react';
import { Router, Route, Link } from 'react-router';

const App = React.createClass({
  render() {
    return (
      <div>
        <h1>My App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/users">Users</Link></li>
        </ul>
        {this.props.children}
      </div>
    );
  }
});

export default App;

In the App.js file, you first need to import the React and React Router modules. Then, you create a React component called App, which renders a navigation bar and the child components.

The child components are rendered inside the App component using the this.props.children property. The this.props.children property is a special property that is provided by React Router. It contains all the components that are rendered by the router.

Subscribe to Tech Break

Next, you need to create the About and Users components. The About component should look like this:

import React from 'react';

const About = React.createClass({
  render() {
    return (
      <div>
        <h2>About</h2>
        <p>This is the about page.</p>
      </div>
    );
  }
});

export default About;

The Users component should look like this:

import React from 'react';

const Users = React.createClass({
  render() {
    return (
      <div>
        <h2>Users</h2>
        <p>This is the users page.</p>
      </div>
    );
  }
});

export default Users;

Now that you have created the App, About, and Users components, you need to wire them up to the router. This is done by creating a file called ‘routes.js‘ in the src directory. The ‘routes.js‘ file should look like this:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './App';
import About from './About';
import Users from './Users';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={About} />
    <Route path="about" component={About} />
    <Route path="users" component={Users} />
  </Route>
);

In the routes.js file, you first need to import the React and React Router modules. Then, you import the App, About, and Users components.

Next, you define a route for each component. The route for the App component is a special route called the index route. The index route is used when the URL matches the root of the application. In this case, the root of the application is “/”.

The route for the About component is defined as /about, and the route for the Users component is defined as “/users”.

Finally, you need to tell React Router to use the routes. This is done by creating a file called ‘main.js’ in the src directory. The ‘main.js’ file should look like this:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';

ReactDOM.render(
  <Router routes={routes} history={browserHistory} />,
  document.getElementById('root')
);

In the main.js file, you first need to import the React, React Router, and router modules. Then, you tell React Router to use the routes and the browser’s history API.

Finally, you render the router into the DOM. The router will automatically render the App component into the DOM, and the App component will render the child components into the DOM.

How react-router works?

React Router provides a Router component that takes a history object as a prop. The history object is responsible for keeping track of the current location in the browser’s history.

The Router component renders a React component based on the current location in the history object.

React Router provides a Link component that can be used to create links to new routes.

React Router provides a Route component that is used to declare a new route.

The Router component is the core of React Router. It is responsible for rendering a React component based on the current location in the history object. The Router component accepts a prop called history. The history object is created by React Router and is responsible for keeping track of the current location in the browser’s history.

The Router component renders a React component based on the current location in the history object. The current location is determined by the browser’s URL. When the current location is updated, the Router will re-render the React component that is associated with the new location.

React Router provides a Link component that can be used to create links to new routes. The Link component accepts a prop called to. The to prop is used to specify the route that the link should lead to.

React Router provides a Route component that is used to declare a new route. The Route component accepts a prop called path. The path prop is used to specify the path that the route should match.

The Route component also accepts a prop called a component. The component prop is used to specify the React component that should be rendered when the route is matched.

The Route component can also be used to render nested routes. To do this, the Route component accepts a prop called render. The render prop is used to specify a function that will be used to render the React component for the route.

The function that is passed to the render prop will be passed two arguments:

  • A first argument is an object that contains information about the current route.
  • A second argument is an object that contains a history object.

The function that is passed to the render prop should return a React element that will be rendered by the Router.


So as of now, We’ve got a basic idea of what the React router is, but there comes two important question-

  1. When to use react-router?
  2. When not to use it?

When to use react-router?

There are a number of situations where react-router is a good choice for routing in your React application.
1. If you are building a single-page application, react-router is a good choice.
2. If you need support for dynamic routing, react-router is a good choice.
3. If you need support for server-side rendering, react-router is a good choice.

When should you not use react-router?

There are also a number of situations where react-router is not the best choice for routing in your React application.
1. If you are not building a single-page application, react-router is not the best choice.
2. If you do not need support for dynamic routing, react-router is not the best choice.
3. If you do not need support for server-side rendering, react-router is not the best choice.

Share this Content
Snehasish Konger
Snehasish Konger

Snehasish Konger is the founder of Scientyfic World. Besides that, he is doing blogging for the past 4 years and has written 400+ blogs on several platforms. He is also a front-end developer and a sketch artist.

Articles: 190

Newsletter Updates

Join our email-newsletter to get more insights