How to Implement React Router Routes

This article provides a straightforward, step-by-step guide on how to implement routing in a React application using the React Router library. You will learn how to install the necessary package, configure the router, define your application routes, and enable seamless navigation between different components without reloading the browser.

Step 1: Install React Router

To get started, you need to install the react-router-dom library, which contains the DOM bindings for React Router. Run the following command in your project terminal:

npm install react-router-dom

Step 2: Set Up the Router

To enable routing across your entire application, you must wrap your root component (usually in main.jsx or index.js) with the BrowserRouter component.

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);

Step 3: Define Your Routes

Inside your main App component, import Routes and Route from react-router-dom. Use these components to map specific URL paths to your page components.

import { Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import NotFound from './pages/NotFound';

function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
        {/* Catch-all route for 404 pages */}
        <Route path="*" element={<NotFound />} />
      </Routes>
    </div>
  );
}

export default App;

To navigate between pages without triggering a full page refresh, use the Link or NavLink component instead of traditional HTML anchor (<a>) tags.

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

function Navigation() {
  return (
    <nav>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>
    </nav>
  );
}

export default Navigation;

Step 5: Handling Dynamic Routes

If you need to pass parameters through the URL (such as a user ID), you can define dynamic routes using a colon (:) followed by the parameter name.

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

Inside the targeted component (e.g., Profile), retrieve the dynamic parameters using the useParams hook:

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

function Profile() {
  const { userId } = useParams();
  
  return <h1>User Profile ID: {userId}</h1>;
}

export default Profile;