bardia riahi
bardia riahi

Reputation: 73

how to dynamic route in react

hello I have a problem with the dynamic router it's my router code

<Router>
    <Navbar />
    <Switch>
        <Route path={`/dashboard/buyList`} component={BuyList} />
        <Route path={`/dashboard/receipt`} component={WarehouseReceipt} />
        <Route path='/dashboard/new' component={NewBuy} exact/>
        <Route path='/dashboard/buyList:id' component={BuyInfo}/>
        <Route path='/dashboard' component={DashboardDetail} exact/>
        <Route component={NotFound} />
    </Switch>
</Router>

my problem is where how I must set buyList:id and define it in my project?

Upvotes: 0

Views: 755

Answers (1)

Ashish Kamble
Ashish Kamble

Reputation: 2627

here is small example how it works in nested routes,

function BuyList () {
  return (
    <div>
      <h1>BuyList</h1>
      <ul>
        {buyList.map(({ name, id }) => (
          <li key={id}>
            <Link to={`/buylist/${id}`}>{name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={`/buylist/:id`}>
        <Buy />
      </Route>
    </div>
  )
}

with react hook,

let { path, url } = useRouteMatch();

  <Switch>
    <Route exact path={path}>
      <h3>Please select a buy.</h3>
    </Route>
    <Route path={`${path}/:buyId`}>
      <Buy />
    </Route>
  </Switch>

and Buy is,

function Buy() {

  let { buyId } = useParams();

  return (
    <div>
      <h3>{buyId}</h3>
    </div>
  );
}

Upvotes: 1

Related Questions