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 */}
<LoggedRouteexactpath = "/"component = {Home}/><Routeexactpath = "/login"component = {Login}/><Routeexactpath = "/groups"component = {Groups}/> {/* This should be exact */}
<Routeexactpath = "/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:
<buttononClick={() => {
history.push(`/groups`)
}}
>
Groups
</button><buttononClick={() => {
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):
importReactfrom'react'import { useParams } from'react-router-dom'exportdefaultfunctionGroupDash() {
let { id } = useParams()
return<>Group Dash: {id}</>
}
Post a Comment for "History.push() And Custom Url Parameters Using React-router"