I am trying to make my react-router work. Until now, I only had simple routes like: /login, /logout, /admin. I have a couple of routes below my /admin route like /admin/users, /admin/groups
Now I would like to make it so I can render a component on a route like this: /admin/groups/modify/:groupID. Since the /admin/groups work just fine, I thought I could just write /admin/groups/modify/:groupID, but it doesn't work that way.
So why does /admin/groups work, but not /admin/groups/modify/:groupID? Is it because I have the parameters?
My router looks like this:
<Router>
<Navbar />
<Switch className = "container-fluid">
<Route exact path = "/" component = {Dashboard} />
<Route exact path = "/login" component = {Login} />
<Route exact path = "/logout" component = {Logout} />
<Redirect from = "/register/" to = "/"/>
<Route exact path = "/register/:token" component = {Register} />
<Route exact path = "/groupview" component = {GroupView} />
<Route exact path = "/admin" component = {AdminDashboard} />
<Route exact path = "/admin/users" component = {AdminUsers} />
<Route exact path = "/admin/groups" component = {AdminGroups} />
<Route exact path = "/admin/groups/modify/:groupID" component = {AdminGroupsModify} />
<Route exact path = "/admin/regTokens" component = {AdminRegTokens} />
</Switch>
</Router>
You should not put that many exact props into your route component,React route always make partial matching and first come first serve which mean if you declare a path /
first and /admin
second it will render the first path component first (even if you want the second it won't render that), that's why you should put exact props in your Route component which you need to match perfectly,This is how you should proceed
export default function App() {
return (
<>
<Router>
<Nav />
<Switch className="container-fluid">
<Route exact path="/admin" component={AdminDashboard} />
<Route path="/admin/regTokens" component={AdminRegTokens} />
<Route path="/admin/users" component={AdminUsers} />
<Route exact path="/admin/groups" component={AdminGroups} />
<Route
path="/admin/groups/modify/:groupID"
component={AdminGroupsModify}
/>
</Switch>
</Router>
</>
);
}
Another way is to put Route which has bigger path first which means putting this Route
<Route path="/admin/groups/modify/:groupID"
component={AdminGroupsModify}
/>
before this Route
<Route exact path="/admin/groups" component={AdminGroups} />
Reference for better understanding of react route
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments