Skip to content

enhsu/React-Router-Foundation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Router Foundation

References

Environment Setting

# create create app
$ npx create-react-app <project-name>
# install react-router-dom version 6
$ npm i react-router-dom@6

Configuring Routes

Foundation

  1. Use BrowserRouter component wraps the App component in index.js
  2. Building Routes & Route structure in App.js
  3. Navigatioin
  4. Handle no match routes in App.js
    • <Route path="*" element={<NoMatch />} />
  5. Nested routing
    • <Outlet> - An <Outlet> should be used in parent route elements to render their child route elements. Outle demo see NestedRoute/index.js
    • If the parent route matched exactly, it will render a child index route, e.g. <Route index element={<IndexCompponent />}>, or nothing if there is no index route. Route index demo see App.js

Advanced - Dynamic Routes

Advanced - Lazy Loading

Using this technique, pages that are not required on the home page can be split out into separate bundles, thereby decreasing load time on the initial page and improving performance.

  • import: const LazyComponent = React.lazy(() => import('/component/path'))
  • Usage: <Route path="path" element={<React.Suspense fallback="Loading..."><LazyComponent /></React.Suspense>} />
  • demo see App.js

Advanced - Authentication & Protected Routes

authenticatioin scenario

Steps

  1. Create auth.js, createContext for global variable
  2. Wrap all App with AuthProvider in index.js
  3. Create Login Page, handle user login
    • NOTE: set replace: true before navigating
    • Reason: Normally a call to navigate will push a new entry into the history stack so the user can click the back button to get back to the page. If you pass replace: true to navigate then the current entry in the history stack will be replaced with the new one.
    • Advanced - useLocation, redirect to the path which the value is from RequireAuth.js
  4. Create Profile Page, handle user logout
  5. Edit App.js, adding the route
  6. Edit Navbar.js
    • user not login -> show Login
  7. Advanced - Create reuseable wrap component RequireAuth.js, for checking user is login
    • the component will render first
    • if user is login -> render children component
    • if user is NOT login -> redirect to login page

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published