DEV Community

Md Yusuf
Md Yusuf

Posted on

1

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay