score:-1

Accepted answer

issue

i think i'm reading between the lines here and guessing/assuming that you are rendering these routes within a switch component. if this is the case then the issue is that the only valid children components of the switch are the route and redirect components. when the postprovider component is reached, route matching ceases and the postprovider component is returned/rendered.

solution

refactor/restructure the components to render the custom privatesroutes component at the switch component level so routes can continued to be matched and rendered. move the postprovider component inside the route.

example:

<switch>
  ... other more specific routes ...
  <route path="/forgot-password">
    <forgetpwd />
  </route>
  <route path="/verifyemail">
    <emailvarification />
  </route>
  <route path="/recover-password">
    <recoverpassword />
  </route>
  <privateroutes path="/dashboard">
    <postprovider> // <-- postprovider moved into route
      <layout>     // <-- layout moved into route
        <dashboard />
      </layout>
    </postprovider>
  </privateroutes>
  <route path="/:id?">
    <publicpage />
  </route>
  ... other routes ...
</switch>

update

<browserrouter>
  <switch>
    <route path={"/home"}>
      <home />
    </route>
    <route path={"/"}>
      {/* i need to add some logic to protect these routes */}
      <switch>
        <route path={"/about"}>
          <about />
        </route>
      </switch>
    </route>
   {/* this below route cannot access */}
    <route path={"/:id"}>
      <publicpage />
    </route>
  </switch>
</browserrouter>

within the switch component path order and specificity matters. the less specific path="/" route is ordered before the "/:id" path, so "/" will always be matched and rendered and any routes listed after will effectively be unreachable.

within switch components you should order the routes by inverse order of path specificity. "/home" is more specific than "/:id" is more specific than "/", and this should be the order for these three routes.

<browserrouter>
  <switch>
    <route path="/home">
      <home />
    </route>
    <route path="/:id}>
      <publicpage />
    </route>
    <route path="/">
      <switch>
        <route path="/about">
          <about />
        </route>
      </switch>
    </route>
  </switch>
</browserrouter>

the same holds true when using custom route components.

example privateroute component:

const privateroute = props => {
  // auth logic
  return isauth ? <route {...props} /> : <redirect to="/login" />;
};

...

<browserrouter>
  <switch>
    <route path="/home">
      <home />
    </route>
    <privateroute path="/about">
      <about />
    </privateroute>
    <route path="/:id}>
      <publicpage />
    </route>
  </switch>
</browserrouter>

Related Query

More Query from same tag