-
Notifications
You must be signed in to change notification settings - Fork 10
Lesson 1.9
This assignment will teach you about React Router, a third-party library. In addition to learning how to install this third-party library, you'll learn how to use it as well.
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-dominstead
yarn add react-router-dom
Read documentation: https://reactrouter.com/web/guides/quick-start
- Open
src/App.jsx - Import
BrowserRouter,Routes, andRoutefromreact-router-dom - Wrap existing JSX within new
BrowserRoutercomponent - Inside
BrowserRouter, wrap existing JSX within newRoutescomponent - Inside
Routes, wrap existing JSX within newRoutecomponent with proppathequal to the root path ("/")-
NOTE:
- In React Router v5 and below, one must provide the
exactproperty on a Route component in order to match the provided path exactly (example:<Route path="/myRoute" ...>matcheshttp://localhost:5173/myRouteand only that url path). Without theexactproperty, 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
Routecomponent, create a newRoutewith path"/new" - Inside the
Routecomponent, 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:5173/new
- Verify that your New Todo List heading appears