Home > Software design >  Why router navigates me into homepage when i'm changing my query params in url reactjs
Why router navigates me into homepage when i'm changing my query params in url reactjs

Time:05-13

I work with React Router V5.

I have implemented React Pagination with url params.

I'm facing issue when i'm changing my query params in url then router redirects into homepage.

Could you tell me what is wrong with my routes?

export const AppRoutes = () => {
  const { currentUser } = useAuth();
  return (
    <Switch>
      {!currentUser.isLoggedIn && <Route path={AppRoute.login} component={Login} />}
      <Layout>
        <Route exact path='/' component={Home} />
        <Redirect to='/' />
      </Layout>
    </Switch>

When i comment redirect line, then my pagination with params works fine.

CodePudding user response:

When the path={AppRoute.login} path isn't matched and rendered by the Switch component the entire Layout component is rendered, then all routes inside are inclusively matched and rendered just like they would be in a router outside any Switch component.

In other words, the Redirect is always matched and rendered, redirecting unconditionally to "/".

You can render the nested routes inside another Switch so exclusive route matching and rendering occurs:

export const AppRoutes = () => {
  const { currentUser } = useAuth();
  return (
    <Switch>
      {!currentUser.isLoggedIn && <Route path={AppRoute.login} component={Login} />}
      <Layout>
        <Switch>
          <Route exact path='/' component={Home} />
          <Redirect to='/' />
        </Switch>
      </Layout>
    </Switch>
  );
};

CodePudding user response:

Something i've used is creating a route component that check this, just to make the code cleaner.

try this...

LoggedOutRoute.js ( useHistory() is imported from react-router-dom )

function LoggedOutRoute({ component: Component, ...rest }) {
    const { currentUser } = useAuth()
    const history = useHistory();
    return (
        <Route
            {...rest}
            render={props => {
                return currentUser.isLoggedIn ? history.replace('/') : <Component {...props} />
            }}
        >
        </Route>
    )
}

export default LoggedOutRoute

This checks if the user is logged in, if so it will redirect to home page, else will continue to the path and component.

AppRoutes.js ( make sure to import LoggedOutRoute.js )

export const AppRoutes = () => {
  return (
    <Switch>
      <LoggedOutRoute path={AppRoute.login} component={Login} />
      <Route exact path='/' component={Home} />
    </Switch>

Hope this helps ;)

  • Related