ReactJS Routing: Getting Started with React Router

by | Feb 21, 2023 | Web Development | 0 comments

Are you new to ReactJS and looking for a way to easily implement routing for your application? If so, then look no further! In this post, we’ll discuss the basics of React Router, a popular library used for managing routes in React applications. We’ll explain the key concepts of React Router, provide an overview of its features, and provide a step-by-step guide on how to get started. With this guide, you’ll be up and running with React Router in no time!

What is React Router?

React Router is a library for routing in React applications. It enables developers to create single-page applications that mimic the behavior of multi-page applications by routing users between different pages or components. It allows developers to define routes and navigate through the app by transitioning from one component to another based on those routes. React Router works with both client-side and server-side rendering, and is available for both React and React Native. With React Router, developers have control over the navigation of their application, allowing them to create powerful, user-friendly apps.

Why use React Router?

React Router is an essential tool for any React application, allowing you to create a single-page application with multiple pages. It simplifies routing and navigation within your application and provides a powerful API that makes creating custom components easy. React Router can help you organize your application structure and give it a natural flow.

React Router gives you the ability to add custom routes that point to different components of your application. This way, you can customize the URLs used for each page in your application and make them more SEO friendly. Additionally, you can use React Router’s Link component to provide navigation links throughout your application, allowing users to easily navigate between different parts of the website.

React Router also makes it easy to handle dynamic route parameters. You can specify which parameters should be accepted, and the router will match the URL path to the corresponding route. This can be extremely useful for managing applications with a lot of content.

Finally, React Router is an open source library, so you can get started with it quickly and easily. With a variety of helpful documentation and community resources, you can get up and running in no time.

Installation

Installing React Router is fairly simple and can be done using npm. To install it, open up your terminal and run the following command:

npm install react-router-dom

After the installation is complete, you need to import the necessary components from React Router into your application. To do so, use the following statement at the top of your application’s entry point:

import { BrowserRouter, Route, Link, NavLink, Redirect, Switch } from ‘react-router-dom’;

You can also use an ES6 syntax for the same statement:

import { BrowserRouter, Route, Link, NavLink, Redirect, Switch } from ‘react-router-dom’;

Now that you’ve imported the necessary components from React Router, you can start setting up the routes in your application.

Getting started

Getting started with React Router is quite simple. First, you’ll need to install the library via npm: 

npm install react-router-dom

Once that’s done, you can now begin using React Router in your project. The library provides two components that help manage the application’s URL – BrowserRouter and HashRouter. 

BrowserRouter is used for web applications that use the HTML5 history API. It is designed to provide a consistent experience between browsers. HashRouter is designed for web applications that don’t use the HTML5 history API, such as legacy browsers. 

To get started, you’ll need to wrap your top-level component in either BrowserRouter or HashRouter depending on the requirements of your project. Here is an example of what this looks like using BrowserRouter: 

import { BrowserRouter } from ‘react-router-dom’;

class App extends Component {

 // Your components here

React Router also provides a few helpful components to assist with navigation. Link is used to create a link to a page while NavLink can be used to create a link that has active styling applied when it matches the current URL. Redirect is used to redirect a user to a different page and Switch is used to group multiple routes together. 

That’s it! With just a few lines of code, you’ve now set up your project with React Router.

BrowserRouter

BrowserRouter is one of the two core routing components in React Router and is used to implement client-side routing. This means that the routing is handled on the client side instead of on the server side. BrowserRouter utilizes the HTML5 History API, which allows it to keep track of the current location and provide a richer user experience.

When you use BrowserRouter in your React app, you’ll provide a single route for the router to render your UI. From there, any navigation in your application will be handled by the Router. This ensures that navigation happens without having to refresh the page and also allows you to maintain a consistent URL throughout your app. 

BrowserRouter can also be used to create dynamic routes, which allow for more complex navigation. These dynamic routes accept parameters, which allow the route to display different content based on what’s provided in the parameter. For example, if you wanted to create a page that displays information about a specific user, you could create a dynamic route that accepts a user ID as a parameter. 

Using BrowserRouter is a great way to make your app more interactive and engaging, while also providing a better user experience. With just a few lines of code, you can enable powerful routing capabilities within your app.

HashRouter

HashRouter is a router component provided by React Router. It is used when we want to use the traditional URL hash style routing. HashRouter uses a # as the delimiter in the URL path which separates the actual path from the route path. It provides more stability when navigating around web pages since it does not cause a full page reload.

To use HashRouter, import it from the react-router-dom package like this:

import { HashRouter } from ‘react-router-dom’

Once imported, you can then wrap the main component of your application in HashRouter. It will look something like this:

This will enable HashRouter to keep track of your URL path and provide the appropriate route. You can then add your own routes using the Route component which is also imported from react-router-dom. HashRouter will take care of the rest, providing a convenient and clean way of navigating through different parts of your application.

Link

Link is a component used in React Router that allows you to navigate to different routes within your application. It’s similar to an anchor tag in HTML, but it works differently with React and the React Router. Link has a few props that you can use to control how it works. 

The most basic use of the Link component is to create a link that navigates to a different route when clicked. To do this, you will need to pass in the ‘to’ prop with the pathname of the route you want to link to. This can be a string or an object depending on what you’re linking to. 

For example, if we want to link to the /about page, we can use Link like this: 

This will create a link that navigates to the /about page when clicked. You can also pass in query strings or other data in the ‘to’ prop using an object instead of a string. For example, if we wanted to add a query string parameter to the /about route, we could use an object like this: 

The Link component also has a few other props you can use to customize how it works. The ‘replace’ prop allows you to replace the current route in the history stack instead of pushing it onto the stack. You can also add a ‘className’ or ‘style’ prop to apply styles or classes to the link element. Finally, the ‘innerRef’ prop allows you to reference the underlying DOM node of the Link component, which is useful for accessing its properties or triggering events. 

Overall, Link is an essential component when working with React Router and is used for creating links within your application. With a few props, you can customize how it behaves and make it fit your needs.

NavLink

NavLink is a component provided by React Router that allows you to link to different routes in your application without refreshing the page. This helps create smooth, intuitive navigation for your users. NavLink provides the same features as Link, but with additional features such as styling active links and automatically applying the active class to the link when it is active. It also passes a “isActive” prop to the link so you can make it have a different style than normal.

The syntax for NavLink looks like this:

The “to” attribute specifies the route path you want the link to point to. The “activeClassName” attribute lets you specify a class name that will be applied when the link is active. The “exact” and “strict” attributes are optional and are used to make sure that the exact route path is matched. 

NavLink is a great tool for creating seamless, intuitive navigation for your users. With its simple syntax and additional features such as styling active links, it is easy to use and perfect for any React application.

Redirect

Redirecting is an important part of using React Router. It allows you to redirect users to different routes, or even different applications, based on certain conditions. Redirects can be triggered by the URL, or based on a state change within the application. 

React Router provides a component called Redirect which can be used to create a redirection from one route to another. This component takes two props: 

1. From – This prop specifies the source path for the redirection. 

2. To – This prop specifies the destination path for the redirection.

In addition to these two props, the Redirect component also accepts a third optional prop called “push”. When this prop is set to true, the new route will be pushed onto the history stack, allowing the user to navigate back and forth between the current page and the redirected page. 

Using the Redirect component is simple: just wrap it around the routes that you want to have redirected. For example: 

 <Route exact path=”/”>

 <Route exact path=”/login”>

 <Redirect from=”/old-path” to=”/new-path” push/>

In this example, any requests made to “/old-path” will be redirected to “/new-path”. The “push” prop ensures that the redirected route is added to the history stack so the user can navigate back and forth between the two pages. 

Redirecting is an essential part of using React Router, and can help ensure your application always serves up the correct page or resource.

Switch

Switch is a React Router component that renders one of its children components, depending on the current location. It takes all the route components passed in as children and renders the first one that matches the current URL. This way, you can easily set up different paths to different components.

Switch is usually used when multiple routes share the same parent path, or when a single route can match multiple paths. For example, if you have an application with a “profile” page, but the user can navigate to different sections of their profile, like “settings”, “billing”, etc., you could use Switch to render the right component for each section. 

When using Switch, you must provide a “path” prop to each of the children, which will be used to determine which component should be rendered. You can also pass props to your components through the Switch component, allowing you to create more complex routing scenarios. 

When working with Switch, it’s important to keep in mind that the order of your routes matters – if two routes have the same path, the first one that was defined will be rendered. 

In summary, Switch is an incredibly useful tool for creating complex routing scenarios in your React applications. It helps you keep your codebase clean and organized, by allowing you to render different components based on the current path. With just a few lines of code, you can quickly build complex, multi-level routing systems in your React apps.