Lesson 1.9
This lesson will teach you the following:
- React Router (a third-party library which you'll learn more about in the next lesson, Lesson 2.1)
When the web started, most websites consisted of a collection of HTML pages that users could navigate through by requesting and opening separate files. The location of the current file or resource was listed in the browser’s location bar.
In a single-page-app (SPA), all of these features become problematic.
Remember, in a single-page app, everything is happening on the same page. JavaScript is loading information and changing the UI. Features like browser history, bookmarks, and forward and back buttons will not work without a routing solution.
Routing is the process of defining endpoints for your client’s requests.
React doesn’t come with a standard router library. A popular routing library called React Router is commonly used. The React Router has been adopted by the community as a popular routing solution for React apps.
The router will allow you to set up routes for each section of the website. Each route is an endpoint that can be entered into the browser’s location bar. When a route is requested, we can render the appropriate content.
The React Router documentation site is your best starting point.
If you're using NPM, run
npm install react-router-dom
instead
yarn add react-router-dom
Read documentation: https://reactrouter.com/web/guides/quick-start
- Open
src/App.jsx
- Import
BrowserRouter
,Routes
, andRoute
fromreact-router-dom
- Wrap existing JSX within new
BrowserRouter
component - Inside
BrowserRouter
, wrap existing JSX within newRoutes
component - Inside
Routes
, wrap existing JSX within newRoute
component with proppath
equal to the root path ("/"
)-
NOTE:
- In React Router v5 and below, one must provide the
exact
property on a Route component in order to match the provided path exactly (example:<Route path="/myRoute" ...>
matcheshttp://localhost:3000/myRoute
and only that url path). Without theexact
property, the path will match any url that starts with the given string (example: the path/
will match all other urls, including/one
,/one/two
, and so on) - In React Router V6, the exact property is no longer required and paths are matched exactly by default. Instead, you may use the wildcard
*
to match any descendant routes. Read more about the differences between V5 and V6 in the migration guide
- In React Router v5 and below, one must provide the
-
NOTE:
- Run your application and view in browser
- Verify that your Todo List still appears correctly
- Open
src/App.jsx
- Below the
Route
component, create a newRoute
with path"/new"
- Inside the
Route
component, create a level-one heading with text "New Todo List" - Run your application and view in browser
- Verify that your Todo List still appears correctly
- Navigate to http://localhost:3000/new
- Verify that your New Todo List heading appears