• Articles
  • Tutorials
  • Interview Questions

How to Use React Router to Navigate?

How to Use React Router to Navigate?

We will delve into the concepts related to react router, covering its installation and setup, while also exploring the fundamental distinctions between react router and DOM. 

Table of Contents

Unlock the magic of React with our enchanting “ReactJS Full Course” video.

Video Thumbnail

What is React Router?

React Router is an essential library for web development using React. It offers a powerful and intuitive solution for handling routing in single-page applications. 

With React Router, developers can create dynamic and interactive user interfaces by synchronizing the application’s UI with the browser’s URL. This allows seamless navigation between different pages and components. React Router follows a declarative approach, making defining and managing routes within the application easier.

Go through these Android Developer Interview Questions to excel in your interview.

Why Do We Need a React Router?

React Router is an indispensable tool in web development using React, serving various purposes that greatly enhance the user experience. Let’s explore with the help of a React Router example:

Imagine you’re building a multi-page application where users can browse and purchase different products. Each product has a details page with a unique URL, such as “/products/123” for product 123. With React Router, you can handle the routing manually, resulting in more convenient and efficient code.

React Router offers a streamlined approach to navigation, enhancing the user experience in the process. By defining routes and associating components with those routes, React Router simplifies the navigation process. For example, you can easily establish a route for the product details page using the following setup:

<Route path="/products/:id" component={ProductDetails} />

The ‘:id’ parameter represents the product’s unique identifier in this example. When a user visits a URL like “/products/123”, React Router captures the ID and passes it to the ‘ProductDetails’ component as a prop.

React Router also provides a way to navigate between different pages within your application. Let’s say you have a list of products displayed on the home page, and when a user clicks on a specific product, you want to take them to the corresponding product details page. With React Router’s ‘Link’ component, you can achieve this seamlessly:

<Link to={`/products/${productId}`}>View Details</Link>

Here, the ‘to’ prop specifies the URL dynamically based on the ‘productId.’ When the user clicks the link, React Router navigates them to the correct product details page without reloading a full page.

Get 100% Hike!

Master Most in Demand Skills Now!

React Router also ensures the URL synchronizes with the application’s UI state. This means that users can bookmark or share specific product pages, and when they revisit the URL, React Router intelligently renders the corresponding components. Hence, this is the main reason why there is high need for react router in the web development domain.

Components in React Router

Components in React Router

React Router consists of three essential components that provide seamless routing in React applications. These components are:

  • BrowserRouter: The BrowserRouter component provides the routing functionality for your application. It uses the HTML5 history API to manage the URL and keep it in sync with the UI. This component should wrap around the root of your application to enable routing capabilities. It listens to changes in the URL and renders the appropriate components based on the specified routes. Here’s a example of how to use the <BrowserRouter> component in React Router:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
const Home = () => <h1>Welcome to the Home Page!</h1>;
const About = () => <h1>About Us</h1>;
const App = () => (
  <BrowserRouter>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
    <Route path="/" exact component={Home} />
    <Route path="/about" component={About} />
  </BrowserRouter>
);

export default App;

In this example, we have a simple React application with two routes: the home route (“/”) and the about route (“/about”). The <BrowserRouter> component wraps the entire application and enables routing. Inside the <BrowserRouter>, we have a navigation bar (<nav>) with two <Link> components. These links will update the URL and render the corresponding components without refreshing the page.

The <Route> components define the mapping between the paths (path=”/”, path=”/about”) and the components (component={Home}, component={About}) to be rendered when the paths match. Remember to install and import the necessary dependencies (react-router-dom) for this code to work properly.

  • Route: The Route component defines the mapping between a URL path and a React component. It determines which component to render based on the current URL. The Route component accepts two main props: “path” and “component.” The “path” prop specifies the URL pattern to match, and the “component” prop sets the React component to render when the URL matches the pattern. The corresponding component is generated when a user navigates to a URL that matches the defined path. Here’s a complete example that demonstrates the usage of the <Route> component in React Router:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
const Home = () => <h1>Welcome to the Home Page!</h1>;
const About = () => <h1>About Us</h1>;
const UserProfile = ({ match }) => (
  <h1>User Profile: {match.params.id}</h1>
);
const App = () => (
  <BrowserRouter>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/users/123">User Profile</Link>
    </nav>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    <Route path="/users/:id" component={UserProfile} />
  </BrowserRouter>
);

export default App;

In this example, we import the necessary dependencies (BrowserRouter, Route, Link) from react-router-dom. We define three components: Home, About, and UserProfile. Inside the <BrowserRouter>, we have a navigation bar (<nav>) with three <Link> components. These links represent different routes in our application.

The <Route> components define the mapping between the paths and the components to be rendered. The first <Route> has exact prop, so it will only match the exact path “/”, rendering the Home component. The second <Route> matches the path “/about”, rendering the About component. The third <Route> has a dynamic path “/users/:id”, rendering the UserProfile component and passing the id as a parameter.

With this setup, when you navigate to different routes using the navigation links, the corresponding components will be rendered based on the matching paths. Remember to install the required dependencies (react-router-dom) and render the App component in your main index.js file or wherever you mount your React application.

  • Link: The Link component creates links within your application, allowing users to navigate different routes. It renders an anchor tag (‘<a>’) with the specified URL, ensuring the application’s UI remains intact without triggering a full page reload. Using the Link component, you can create navigational links that seamlessly update the URL and trigger the rendering of the corresponding component without disrupting the user’s experience. Here is the example of link component in react router:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
const Home = () => <h1>Welcome to the Home Page!</h1>;
const About = () => <h1>About Us</h1>;
const App = () => (
  <BrowserRouter>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
  </BrowserRouter>
);

export default App;

In this example, we import the necessary dependencies (BrowserRouter, Route, Link) from react-router-dom. We define two components: Home and About. Within the <BrowserRouter>, there is a navigation bar (<nav>) that includes two <Link> components. These links represent the routes in our application. Whenever a link is clicked, it updates the URL without refreshing the page.

The <Route> components define the mapping between the paths and the corresponding components to be rendered. The first <Route> uses the exact prop, which ensures an exact match for the path “/”, rendering the Home component. The second <Route> matches the path “/about”, rendering the About component. 

With this setup, whenever a navigation link is clicked, the respective component will be rendered based on the URL path. Remember to install the required dependencies (react-router-dom) and render the App component in your main index.js file or wherever you mount your React application.

How to Install React Router?

To install React Router in your project, you can follow these steps:

  • Create a React Project: First, make sure you have a React project set up. If you don’t have one, you can create a new React project using Create React App or any other preferred method. Open your project in your favorite code editor.
  • Install React Router: Open the terminal or command prompt and navigate to your project’s root directory. Run the following command to install React Router as a dependency:
npm install react-router-dom

This command installs the react-router-dom package, which includes the necessary components for web development with React Router.

  • Import React Router Components: In your React application, you need to import the required React Router components. Open the file where you want to use React Router, typically the main or component files. Add the following import statements at the top of the file:
import { BrowserRouter, Route, Link } from 'react-router-dom';

These import statements make the BrowserRouter, Route, and Link components available in your application.

  • Wrap your App Component with BrowserRouter: In your main file (usually App.js or index.js), wrap your root component with the BrowserRouter component. This allows React Router to manage the routing functionality for your entire application. Modify your code to wrap your root component with BrowserRouter like this:
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
  • Start Building with React Router: With React Router successfully installed and set up, you can now utilize its components to handle routing in your application. Use the Route component to define routes and their corresponding components, and the Link component to create navigation links between routes.

That’s it! You have installed React Router and are ready to build dynamic and navigable applications.

How to Set Up a React Router?

Once react-router is installed, to set up react-router in your project; you can follow these steps:

  • Create a Routing Configuration: Decide the routes you want to implement in your application. Create a new file in the project’s source directory (e.g., “Routes.js”) to define your routing configuration. In this file, import the necessary React Router components:
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
  • Define Routes: Inside the “Routes.js” file, use the Router, Switch, and Route components to define your routes. The Router component wraps your application and provides routing functionality. The Switch component ensures that only one Route is rendered at a time. Each Route component represents a specific path and its corresponding component:
function Routes() {
  return (
    <Router>      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </Router>
  );

}

In this example, the “/” path corresponds to the Home component, “/about” corresponds to the About component, and “/contact” corresponds to the Contact component.

  • Integrate Routes: Return to your main App.js or index.js file and import the Routes component. Render the Routes component within your application:
import Routes from './Routes';
function App() {
  return (
    <div className="App">
      <Routes />
    </div>
  );
}
  • Start the Application: Start your React application using the appropriate command (e.g., ‘npm start’). React Router is now set up and ready to handle routing in your application based on the defined routes.

Difference Between React Router and React Router DOM

Difference Between React Router and React Router DOM

Here are the key differences between React Router and React Router DOM:

  • Purpose: React Router is the core package that provides routing functionality for React applications, while React Router DOM is a specific implementation of React Router for web development. The React Router DOM includes components specifically designed for web routing, such as BrowserRouter and HashRouter.
  • Platform: React Router is platform-agnostic and can be used with different platforms, including web, mobile, and desktop. React Router DOM, on the other hand, is tailored specifically for web applications and provides components that work with web browsers.
  • Components: React Router provides a set of fundamental routing components that can be used across different platforms. React Router DOM extends these components and adds web-specific components, such as BrowserRouter, HashRouter, Link, NavLink, etc., optimized for handling web routing scenarios.
  • URL Handling: React Router allows you to route and navigate between different views/components within your application. It synchronizes the application’s UI with the URL, enabling seamless navigation. As a web-specific implementation, React Router DOM uses the browser’s history API to handle URLs and provide features like browser history management and URL routing.
  • Installation: React Router is installed using the package name “react-router,” while React Router DOM uses “react-router-dom.” React Router DOM is a dependency of React Router and includes additional web-specific functionality on top of the core React Router package.
  • Dependencies: React Router has minimal dependencies and focuses on providing core routing functionality. React Router DOM, on the other hand, has additional dependencies specific to web development, such as history, prop-types, and DOM-related packages, which are needed for web routing features.
  • Server-side Rendering (SSR) Support: React Router supports server-side rendering (SSR) and provides components and utilities for rendering routes on the server. It allows you to handle routing on the server and send the pre-rendered HTML to the client. React Router DOM, being a web-specific implementation, does not include built-in support for server-side rendering.

Conclusion

React Router is an indispensable tool for creating seamless navigation within React applications. This complete guide has shed light on its purpose, emphasizing the need for its implementation. Installing and setting up React Router is a straightforward process that empowers developers to build sophisticated single-page applications. Lastly, understanding the distinction between React Router and React Router DOM ensures the appropriate selection for specific application requirements. Embrace React Router’s potential and elevate your web development game!

Course Schedule

Name Date Details
Web Development Courses 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.