Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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}</>
}

Post a Comment for "History.push() And Custom URL Parameters Using React-router"