Creating Dynamic Routes in React


  In React, dynamic routes allow you to create routes that can change based on certain parameters, such as an ID or a username, rather than being static, predefined routes. This is especially useful for applications like blogs, online stores, or any other type of dynamically generated content.


What are Dynamic Routes?

  Dynamic routes allow you to capture and use parameters in the URL, which can then be used to load specific content or change the application's behavior. Instead of a fixed route, a pattern with a parameter that can be read from the URL is used.


  • Example of a dynamic route: A URL like `/product/:id` where the `:id` parameter is dynamic and can be changed according to the product to be displayed.
  • Using React Router: To handle dynamic routes, we use React Router, which allows us to declare routes with parameters.

  Let's look at an example of how dynamic routes can be defined using React Router:

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/product/:id" component={ProductPage} />
      </Switch>
    </Router>
  );
};
const ProductPage = ({ match }) => {
  const { id } = match.params;
  return <h2>Product ID: {id}</h2>;
};

Accessing Route Parameters

  To access the parameters of a dynamic route, we can use the `match` object that React Router passes to the components it renders. This object contains a `params` field where we can find the URL parameters.


  In the previous example, when the URL is something like `/product/123`, the `id` parameter will be equal to `123`.


Creating Dynamic Routes with Optional Parameters

  React Router also allows creating routes with optional parameters, meaning it is not always necessary to pass a value for that particular parameter.

<Route path="/product/:id?" component={ProductPage} />

  In this case, the `:id` parameter is optional, meaning we can navigate to a route like `/product` without needing to specify an `id`.


Combining Static and Dynamic Routes

  It is common to combine static and dynamic routes within the same application. This allows handling fixed content pages, such as the homepage, along with dynamic pages, such as a product page.

<Route path="/" component={HomePage} />
<Route path="/product/:id" component={ProductPage} />


What is a dynamic route in React? What are routes in React? How to set dynamic style in React? Is it possible to configure routes programmatically in React? React router-dom React routes