DEV Community

Md Yusuf
Md Yusuf

Posted on

Dynamic Routes and Parameters in React Using React Router

In React, dynamic routes and parameters are typically implemented using React Router. Here's how you can set up dynamic routes and capture route parameters.

1. Install React Router

First, you need to install react-router-dom:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

2. Basic Setup

In your App.js (or main component), wrap your routes with the BrowserRouter and define your routes using Route.

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './components/Home';
import UserProfile from './components/UserProfile';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        {/* Dynamic route with parameter */}
        <Route path="/user/:id" element={<UserProfile />} />
      </Routes>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Creating Components

Here, UserProfile is a component that captures the dynamic parameter :id from the route. You can access this parameter using useParams().

// UserProfile.js
import React from 'react';
import { useParams } from 'react-router-dom';

const UserProfile = () => {
  const { id } = useParams();

  return (
    <div>
      <h1>User Profile</h1>
      <p>User ID: {id}</p>
    </div>
  );
};

export default UserProfile;
Enter fullscreen mode Exit fullscreen mode

4. Navigating Between Routes

To navigate between routes, use the Link component from react-router-dom.

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

const Home = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <Link to="/user/1">Go to User 1's Profile</Link>
    </div>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Key Points

  • Dynamic segments in URLs are defined with a colon (:id).
  • Use useParams() to access route parameters in a component.
  • Use Routes and Route to define and manage different routes.

Top comments (0)