Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use :params in React router

Having issues with the react-router picking up on a nested route. A param is passed to accommodate for any subsequent links to be conditionally rendered later in the child component passed into Route

import React from "react";

import { Route } from "react-router-dom";

import CollectionsOverview from "../../components/collections-overview/collections-overview";
import CollectionPage from "../collection/collection";

const ShopPage = ({ match }) => {
  return (
    <div className="shop-page">
      <Route exact path={`${match.path}`} component={CollectionsOverview} />
      <Route path={`${match.path}/:collectionId`} component={CollectionPage} />
    </div>
  );
};
export default ShopPage;

import React from "react";
import "./collection.styles.scss";

const CollectionPage = ({ match }) => {
  return (
    <div className="collection-page">
      <h2>COLLECTION PAGE: {match.params.collectionId}</h2>
    </div>
  );
};

export default CollectionPage;

Route 2 never renders its component on route manipulation

like image 531
dougofi Avatar asked Jun 12 '26 19:06

dougofi


1 Answers

You can use useParams. Please check this example:

import React from "react";
import {BrowserRouter as Router,Switch,Route,Link,useParams} from "react-router-dom";

export default function ParamsExample() {
  return (
    <Router>
      <div>
        <h2>Accounts</h2>
        <ul>
          <li>
            <Link to="/netflix">Netflix</Link>
          </li>
          <li>
            <Link to="/zillow-group">Zillow Group</Link>
          </li>
          <li>
            <Link to="/yahoo">Yahoo</Link>
          </li>
          <li>
            <Link to="/modus-create">Modus Create</Link>
          </li>
        </ul>
        <Switch>
          <Route path="/:id" children={<Child />} />
        </Switch>
      </div>
    </Router>
  );
}

function Child() {
  let { id } = useParams();

  return (
    <div>
      <h3>ID: {id}</h3>
    </div>
  );
}

Source

like image 152
Khabir Avatar answered Jun 15 '26 10:06

Khabir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!