0

I'm learning React making a small single page app. Just added react-router-dom today and building it out to do routes and private routes. All is well except for one thing: When the user enters a malformed url in the browser bar, the user should be rerouted to the index (WORKS!), but the browser url bar is not updated on this redirect. Oddly enough, when I hit a private route while not authorized, the redirect DOES update the url bar. What am I missing?

router.js:

const PrivateRoute = ({auth: authenticated, component: Component, ...rest}) => (
    <Route {...rest} render={(props) => (
        authenticated === true
            ? <Component {...props} />
            : <Redirect to='/login/'/>
    )}/>
);

export default function Router() {

    const auth = useSelector(isAuthenticated);

    return (
        <Switch>
            <PrivateRoute auth={"auth"} path={"/dashboard/"} component={DashboardContainer}/>
            <Route path={"/about/"} component={AboutContainer}/>
            <Route path={"/login/"} component={LoginContainer}/>
            <Route path={"/terms/"} component={TermsContainer}/>
            <Route path={"/"} component={IndexContainer}/>
            <Redirect push to={"/"}/>
        </Switch>
    );
}
Eric
  • 541
  • 6
  • 21

1 Answers1

1

I believe your issue is a result of not specifying that the paths should be exact matches, therefore any route will match with your route that is specified as:

<Route path={"/"} component={IndexContainer}/>

Try adding the exact prop to all of your routes (except for your redirect), and you should properly get redirected to the home page with the correct URL.

More details on the exact prop here: React : difference between <Route exact path="/" /> and <Route path="/" />

Robert Cooper
  • 1,852
  • 1
  • 5
  • 18