简体   繁体   中英

Conditional Route not rendering the redirected Layout

In AppRouter , I have a conditional route with redirect for <AdminLayout/> .

relevant snippet:

<Route
          exact
          path="/admin"
          strict
          render={(props) => <AdminLayout {...props} />}
        >
          {loggedIn ? <Redirect to="/admin/summary" /> : <Login />}
        </Route>

If loggedIn is true then, redirect to /admin/summary else redirect it back to <Login/>

The problem is: it is only changing the URL but not rendering the <AdminLayout/> .

Not sure where I am going wrong and what I am missing.

UPDATED PrivateRoute and AppRouter below

AppRouter

import React, { useEffect } from "react";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { createBrowserHistory } from "history";

import { alertActions } from "../actions";
import { history } from "../helpers";

import AdminLayout from "layouts/Admin/Admin.js";
import AuthLayout from "layouts/Auth/Auth.js";
import ResetPassword from "../components/pages/reset-password/ResetPassword";
import MailReset from "../components/pages/reset-password/MailReset";
import PrivateRoute from "../routes/PrivateRoute";
import Dashboard from "views/Dashboard";

const hist = createBrowserHistory();

const AppRouter = () => {
  const alert = useSelector((state) => state.alert);
  const dispatch = useDispatch();

  useEffect(() => {
    history.listen((location, action) => {
      // clear alert on location change
      dispatch(alertActions.clear());
    });
  }, []);

  return (
    <Router history={hist}>
      <Switch>
        {/* <Route path="/admin" render={(props) => <AdminLayout {...props} />} /> */}
        <PrivateRoute exact path="/admin">
          <Dashboard />
        </PrivateRoute>
        <Route
          path="/auth/login"
          render={(props) => <AuthLayout {...props} />}
        />
        <Route exact path="/auth/forgotPassword" component={ResetPassword} />
        <Route exact path="/auth/mail_reset" component={MailReset} />
        <Redirect from="*" to="/auth/login" />
      </Switch>
    </Router>
  );
};

export default AppRouter;

PrivateRoute

import React from "react";
import { Route, Redirect } from "react-router-dom";

import AdminLayout from "../layouts/Admin/Admin";

function PrivateRoute({ component: Component, roles, ...rest }) {
  console.log("rest pvt route", ...rest);
  return (
    <Route
      {...rest}
      render={(props) => {
        console.log("propsssss", props);
        // if (!localStorage.getItem('userid')) {
        if (!localStorage.getItem("access_token")) {
          // not logged in so redirect to login page with the return url
          return (
            <Redirect
              to={{ pathname: "/auth/login", state: { from: props.location } }}
            />
          );
        }

        // logged in so return component
        return <AdminLayout {...props} />;
      }}
    />
  );
}

export default { PrivateRoute };

So trying to explain what its is wrong:

  1. You are setting rendering child and render props that's why children props takes priority here:
<Route
          exact
          path="/admin"
          render={(props) => <AdminLayout {...props} />}
        >
          {loggedIn ? <Redirect to="/admin/summary" /> : <Login />}
        </Route>
  1. Your private route is correct but need to add your layout as well:
return <AdminLayout {...props} /><Component {...props} /></AdminLayout/>;
  1. Inside app route you need to import PrivateRoute component it will look like this:
import PrivateRoute from './PrivateRoute';

const AppRouter = () => {
  const alert = useSelector((state) => state.alert);
  const loggedIn = useSelector((state) => state.authentication.loggedIn);

  const dispatch = useDispatch();

  useEffect(() => {
    history.listen((location, action) => {
      // clear alert on location change
      dispatch(alertActions.clear());
    });
  }, []);

  return (
    <Router history={hist}>
      <Switch>
        <PrivateRoute exact path='/admin'>
          <YOUR AUTH COMPONENT WHICH YOU WANT TO RENDER />
        </PrivateRoute>
        <Route
          path='/auth/login'
          render={(props) => <AuthLayout {...props} />}
        />
        <Route exact path='/auth/forgotPassword' component={ResetPassword} />
        <Route exact path='/auth/mail_reset' component={MailReset} />
        <Redirect from='*' to='/auth/login' />
      </Switch>
    </Router>
  );
};

        

Here I created demo code of this. Take reference from it: https://codesandbox.io/s/react-router-redirects-auth-forked-6q6o4?file=/example.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM