# create create app
$ npx create-react-app <project-name>
# install react-router-dom version 6
$ npm i react-router-dom@6
- Use
BrowserRouter
component wraps theApp component
in index.js - Building
Routes & Route
structure in App.js - Navigatioin
- About path
If the to path starts with
"/"
, then it's anabsolute path
, otherwise arelative path
- see navlink detail see here
- navigating programmatically see here
- About path
If the to path starts with
- Handle
no match routes
in App.js<Route path="*" element={<NoMatch />} />
- 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
- Handle dynamic routing:
<Route path="/page/:id" />
. dynamic routing demo see App.js - Get URL parameters:
useParams()
- Reference - userParams
- userParams() demo see Users/UsersDetail.js
- Get & Set search parameters:
useSearchParams()
- Reference - useSearchParams
- userSearchParams() demo see Users/index.js
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
Steps
- Create auth.js, createContext for global variable
- Wrap all App with AuthProvider in index.js
- 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
- NOTE: set
- Create Profile Page, handle user logout
- Edit App.js, adding the route
- Edit Navbar.js
- user not login -> show
Login
- user not login -> show
- 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