Nakul Upadhya
Nakul Upadhya

Reputation: 488

history.push() and Custom URL parameters using react-router

I'm trying to create an app where users can join groups, and one of the pages I have is a group dashboard. For this, I created a route with a URL parameter of id.

<Router>
    <div>
        <LoggedRoute exact path = "/" component = {Home}/>
        <Route exact path = "/login" component = {Login}/>
        <Route exact path = "/groups/:id" component = {GroupDash}/>
    </div>
</Router>

When a user creates a group, it persists it in my database, and gets the docID to use as the url parameter.

I then use history.push("/groups/".concat(docID)) to attempt to re-direct my user to the new page. However, this doesn't work and instead takes me to .../groups/ vs .../groups/docID.

I initially thought that this was because the string, docID wasn't being created properly, but after logging the string to the console, it is correct.

Can someone help me with this?

Upvotes: 3

Views: 5615

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

You didn't use Switch, I am not sure why. Here is how to use URL Parameters correctly in react-router:

Routes:

<Router>
  <Switch> {/* Use Switch */}
    <LoggedRoute exact path = "/" component = {Home}/>
    <Route exact path = "/login" component = {Login}/>
    <Route exact path = "/groups" component = {Groups}/> {/* This should be exact */}
    <Route exact path = "/groups/:id" component = {GroupDash}/> {/* This exact can be optional for this use case */}
  </Switch>
</Router>

And you can do history.push to go to that route:

<button
  onClick={() => {
    history.push(`/groups`)
  }}
>
  Groups
</button>
<button
  onClick={() => {
    history.push(`/groups/${1234}`)
  }}
>
  Groups dashboard
</button>

And to get the id in your component, you can use useParams hook or use withRouter HOC (use props.match.params?.id for the HOC):

import React from 'react'
import { useParams } from 'react-router-dom'

export default function GroupDash() {
  let { id } = useParams()

  return <>Group Dash: {id}</>
}

Upvotes: 4

Related Questions