0

I am trying to separate my routes depending on views. To be specific I have created an admin view where I am going to have different routes for admin only. I am trying to use multiple switches but I keep getting 404.

The following is how I am doing:

App.js

<div className="App">
    <Switch>
        <Route exact path="/admin/dashboard" component={ AdminPanel } />
        <Route component={ NoMatch } />
    </Switch>
</div>

AdminPanel.js

<Link to="/admin/dashboard" className="sidebar-item">...</Link>
<Link to="/admin/dashboard/exams" className="sidebar-item">...</Link>
.
.
.
<div className="admin-content">
    <Switch>
        <Route exact path="/admin/dashboard" component={ Dashboard } />
        <Route exact path="/admin/dashboard/exams" component={ Exam } />
    </Switch>
</div>

When I visit localhost:3000/admin/dashboard I get to see the Dashboard component. But when I navigate to localhost:3000/admin/dashboard/exams I am greeted with the 404 page.

Where am I going wrong?

Ayan
  • 2,738
  • 3
  • 35
  • 76

1 Answers1

1

App.js:


<Switch>
    <Route path="/admin/dashboard" component={ AdminPanel } />
    <Route path="/404" component={ NoMatch } />
    <Route component={ NoMatch } />
</Switch>

AdminPanel.js

import {Redirect} from 'react-router-dom'

<Switch>
    <Route exact path="/admin/dashboard" component={ Dashboard } />
    <Route exact path="/admin/dashboard/exams" component={ Exam } />
    <Route render={({location}) => <Redirect to={{
      pathname: '/404',
      state: { originalUrl: location.pathname}
    }} />} />
</Switch>

later in the NoMatch component, you can access it under props.location.state.originUrl

StackedQ
  • 3,999
  • 1
  • 27
  • 41
  • it does seem to do the trick! But I have two questions: 1) What if I would like to preserve the URL which is causing the 404? 2) Is there a way in which I don't have to explicitly mention a redirect to 404? – Ayan Aug 10 '20 at 18:34
  • Using `` renders the 404 page inside admin content container. Redirection works the way I want. – Ayan Aug 10 '20 at 18:44
  • Is there a way to have only one mention of 404 to handle all no match cases? And how do I preserve the URL of not found url – Ayan Aug 10 '20 at 18:51
  • what to do after accessing the `props.location.state.originUrl`? – Ayan Aug 12 '20 at 10:30
  • Then you can do whatever you meant by "What if I would like to preserve the URL which is causing the 404" – StackedQ Aug 12 '20 at 11:07
  • Transform URL from "/404" to "/wrong-url". Possible right? – Ayan Aug 12 '20 at 11:17
  • Yeah, you can name it anything, keep in mind though you gotta change matching route path as well – StackedQ Aug 12 '20 at 12:01
  • Check this for what I am trying to achieve: https://stackoverflow.com/questions/63374142/maintain-url-in-address-bar-when-url-not-found?noredirect=1#comment112062152_63374142 – Ayan Aug 12 '20 at 12:07