React Router - 404 page renders first on protected route

Viewed 389

I have /control-panel page protected but when I go to /control-panel page 404 page renders first then loads the page, any idea how to fix?

code:

  <Switch>
    <Route exact path='/' component={HomePage} />
    <Route exact path='/help' component={FAQ} />

    {admin ? <PrivateRoute authed={userSignedIn} path="/control-panel" exact component={ControlPanel} /> : null}

    <Route component={NoMatch} />
  </Switch>

Updated to:

{!my_protected_urls.includes(window.location.pathname) && <Route component={NoMatch} />}
2 Answers

Make sure that 'admin' value is set before the router initialized and try this.

<Switch>
  <Route exact path='/' component={HomePage} />
  <Route exact path='/help' component={FAQ} />

  {admin ? <PrivateRoute authed={userSignedIn} path="/control-panel" exact component={ControlPanel} /> : null}

  <Route component={NoMatch} />
</Switch>

This is happening as the value of admin is not true before this code is executed.

As I indicated in my comment, it depends on how you are getting value of admin

An easier workaround for the situation, however, will be using pathname.

Try this:

<Switch>
    <Route exact path='/' component={HomePage} />
    <Route exact path='/help' component={FAQ} />

    {admin ? <PrivateRoute authed={userSignedIn} path="/control-panel" exact component={ControlPanel} /> : null}

    {window.location.pathname!=='/control-panel' && <Route component={NoMatch} />}
  </Switch>

This should fix your issue. Cheers!!

Related