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>
    );
}

1 Answer 1

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="/" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.