Skip to content

ServerlessReact.dev

Student Login
  • Intro
  • Project setup
  • Styling with TiaUI
  • Queries
  • Routing
  • Forms
  • Fin

Routing

For routing we use React Router.

It's become the de-facto standard unless you're using a framework like Gatsby or NextJS. They use derivatives of react router.

Declarative routing works by rendering <Route> components with a path prop. The router matches these to your URL and decides what to render. Completely client-side.

Exercise

Make it so users can browse through breeds of doggos.

List all breeds on the homepage. Use https://dog.ceo/api/breeds/list/all – you can ignore the 2nd layer of results.

Link each breed to its own page that renders <Doggos />.

You'll need to wrap the app in <Router>, then use a <Switch>. Change <Doggos /> so it reads the breed from params.

const history = createBrowserHistory()
// ...
;<Router history={history}>
{/* ... */}
<Switch>
<Route path="/:breed" children={Doggos} />
<Route path="/" children={BreedList} />
</Switch>
</Router>
// ...
const { breed } = useParams<{ breed: string }>()

You can then use this breed param in your query.

useQuery(["breeds", breed], async () => fetchBreed)

Solution

You can find my solution at https://github.com/AskTia/tia-react-train/tree/solution-routing

Did you enjoy this chapter?

Previous:
Queries
Next:
Forms
Created bySwizecwith ❤️