How to Use React Router for Smooth Navigation (Step-by-Step Guide)

Programming
Published in Blog on February 10, 2025 3 min read
How to Use React Router for Smooth Navigation

Introduction

Efficient navigation is a key component of any web application, and React Router makes it simple. In this step-by-step guide, we’ll explore how to set up a React Router, define routes, and navigate smoothly within a React app.

 

1. Installing React Router

To get started, install React Router using npm:

npm install react-router-dom

 

2. Setting Up Routes

Wrap your application with <BrowserRouter> and define routes using <Routes> and <Route> components:

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

import Home from './Home';

import About from './About';

 

function App() {

  return (

    <Router>

      <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

      </Routes>

    </Router>

  );

}

 

export default App;

 

3. Navigating Between Pages

Use the <Link> component instead of <a> tags to ensure smooth navigation without reloading the page:

import { Link } from 'react-router-dom';

 

function Navbar() {

  return (

    <nav>

      <Link to="/">Home</Link>

      <Link to="/about">About</Link>

    </nav>

  );

}

 

4. Programmatic Navigation

Use the useNavigate hook to navigate programmatically within your application:

import { useNavigate } from 'react-router-dom';

 

function Dashboard() {

  const navigate = useNavigate();

 

  const goToProfile = () => {

    navigate('/profile');

  };

 

  return <button onClick={goToProfile}>Go to Profile</button>;

}

5. Handling Dynamic Routes

React Router allows dynamic parameters in URLs. Define a route with a dynamic segment:

<Route path="/user/:id" element={<UserProfile />} />

 

Retrieve the parameter using the useParams hook:

import { useParams } from 'react-router-dom';

 

function UserProfile() {

  const { id } = useParams();

  return <h1>User ID: {id}</h1>;

}

 

6. Implementing Nested Routes

Nested routes help create structured layouts with shared components:

<Route path="/dashboard" element={<Dashboard />}>

  <Route path="profile" element={<Profile />} />

</Route>

 

Conclusion

By following this step-by-step guide, you can easily set up React Router for smooth navigation in your React applications. With tools like <Link>, useNavigate, and dynamic routes, you can create a smooth and efficient user experience.

Start integrating React Router today and enhance your app’s navigation!

 

Hi...

Got ideas? We’ve got
the skills. Let’s team up.

Have a question or ready to discuss your project? Our team is here to help you scope, design, and deliver.

Trusted by Leading Businesses
Metro
Zabeel Equstrian
GEMS Logo
APSG Logo
Anisia Logo
Foodlinx Logo
🌐 +1
Select Subject?
send mail graphic