React Router v5.0 Nested Routes

后端 未结 4 1545
天涯浪人
天涯浪人 2020-12-15 01:30

I\'m building a react app and I can\'t make the routing work.

  1. I need one common layout (header, footer) for a few Auth routes (/login, si

4条回答
  •  攒了一身酷
    2020-12-15 01:57

    Each of your layout should have a path component to differentiate from other layouts.

    For example

    Auth layouts could reside under /auth eg, login would /auth/login, signup would be /auth/signup

    App layout could go under /app eg, dashboard would be /app/dashboard, home would be /app/home

    Working Demo

    App.js

    import { Switch, BrowserRouter, Route, Redirect } from "react-router-dom";
    
    function App() {
      return (
        
          
        
      );
    }
    

    Layouts.js

    const NotFound = () => 

    Not Found

    ; function Layouts() { return ( ); }

    AuthLayout

    const Signup = () => 

    Login

    ; const Login = () =>

    Sign up

    ; function AuthLayout() { return (

    Auth Layout

    ); }

    AppLayout

    const Home = () => 

    Home

    ; const Dashboard = () =>

    Dashboard

    ; function AppLayout() { return (

    App Layout

    ); }

    Also if you want to protect certain routes from being rendered if not authenticated, then you can create a PrivateRoute component that would redirect to auth layout if not authenticated.

    PrivateRoute.js

    const PrivateRoute = ({ component: Component, ...rest }) => (
       sessionStorage.token // your auth mechanism goes here
          ? 
          : }
      />
    );
    

    You can use this PrivateRoute component instead of react-router's Route component.

    Eg:

提交回复
热议问题