So far our Pokedex app only has a single page.
Let's make this more interesting…
We want to define distinct pages within our application.
The current page at a given time is defined by the URL of the browser tab.
The URL can contain parameters which are used by a page to show specific data.
React itself does not provide routing.
The most popular routing library in the React ecosystem is React Router.
React Router can be used in two different manners:
We will start with this.
→ Will be covered in chapter 10
createBrowserRouter creates an instance of a router that will be used.
Here we define a route with the path /page1 and tell it to render the Page1 component .
Page1.tsx
The "page" is just a normal React component.
This route has a parameter carId .
CarDetailPage.tsx
The useParams Hook returns the parameters of the current route as an object.
With the Navigate component, a route can be redirected to another route.
With using the replace prop, no entry will be added to the browser history.
const router = createBrowserRouter([...]);
<RouterProvider router={router} />
{path: '/cars/:carId', element: <Car/>}
<Navigate to="/cars" replace />
<Link to="/cars/42">Go to Car 42</Link>
https://github.com/webplatformz/react-pokedex-vite/tree/chapter-05-routing/src/mockData
Think about what to do with the username input and display functionality.
Can we have the input on a Profile page but show the name on all pages?
App.tsx
Layout.tsx
ListPage.tsx
PokeListEntry.tsx
DetailPage.tsx
A NavLink is marked with the specified CSS class/style when its route is active.
Current URL: /cars?filter=Porsche
Returns the location object representing the current URL.
Navigate programmatically
Current URL: /cars?filter=Porsche
Read and write search params using the standard URLSearchParams interface.
Use instead of BrowserRouter for tests.
No official guidelines on React.dev
For component structure & hierarchy, align as closely as possibly with the UX & UI experts on the team. A very common approach is Atomic Design
Evolve your folder structure as you need it
We learned…