Darkbound
Darkbound

Reputation: 3434

Page not found in nested Routes

I am trying to setup some nesting routing in my app and for some reason I can't get it to open my nested pages.

In index.js

<Router>
  <Switch>
    <Route exact path="/" component={App}/>
    <Route path="/admin" component={AdminApp}/>
    <Route component={() => { return <div>Page not found</div>}}/>
  </Switch>
</Router>

In AdminApp.jsx:

import ViewUser from "./ViewUser";

export default function AdminApp({ match }) {
    const [users, setUsers] = useState([]);

    useEffect(() => {...axios to get users from db and setUsers()...}, [])

    return (
    <>
      <div>User</div>
      <Link to={`${match.url}/users/view/${user.Name}`>View</Link>
      <Switch>
        <Route path={`${match.path}/users/view/:username`} component={ViewUser}/>
      </Switch>
    </>) 
}

ViewUser component is a child of the AdminApp component.

And whenever I click on the View link, it changes my url to http://localhost:3001/admin/users/view/theusernameoftheselecteduser , so the url itself (at least in the browser bar) is correct, but it renders the Page not found route and it never renders the ViewUser component. I have a console.log inside it, it does not get triggered at all.

Edit: The accepted answer on this question is what I am trying to do Nested routes with react router v4 / v5 but for some reason I can't get it to work.

https://reactrouter.com/web/example/nesting same example by react-router and I cant get it to work

Upvotes: 0

Views: 241

Answers (2)

Daniel Pantalena
Daniel Pantalena

Reputation: 429

Your application will always render one Route of Switch. When don't match anything, it will render the not found page.

Add the route as a child of Switch, then when the path match it will render the component instead of 'Not found'

<Router>
  <Switch>
    <Route exact path="/" component={App}/>
    <Route exact path="/admin" component={AdminApp}/>
    <Route path={`/admin/users/view/:username`} component={ViewUser}/>
    <Route component={() => { return <div>Page not found</div>}}/>
  </Switch>
</Router>

Upvotes: 1

technicallynick
technicallynick

Reputation: 1592

Remove the exact prop from your admin route. With the exact prop set, fails to match with anything after /admin.

Upvotes: 0

Related Questions