CodeBlanks Logo Icon CodeBlanks

Defining routes

Learn to set up a route tree with Routes and Route.

Defining routes

To define multiple routes, you add multiple <Route>s inside <Routes>. Each Route takes a path and an element.

Example: <Route path="/" element={ '{ <Home /> }' } />, <Route path="/about" element={ '{ <About /> }' } />, <Route path="/contact" element={ '{ <Contact /> }' } />.

When the URL changes, React Router picks the best match. If /about is opened, the About component renders. If no route matches, nothing renders (or a 404 route is defined).

404 route

A 404 route can be defined for unmatched URLs. <Route path="*" element={ '{ <NotFound /> }' } /> catches all unmatched paths.

* is a wildcard; it matches any URL. It's important to put this route last; because React Router matches top to bottom.

A 404 page prevents users from getting lost. It contains a "Page not found" message and a link back home. This matters for user experience.

Practice Define three routes

Complete the skeleton. Write an App component. Inside <Routes>, define three routes: <Route path="/" element={ '{ <Home /> }' } />, <Route path="/about" element={ '{ <About /> }' } />, <Route path="*" element={ '{ <NotFound /> }' } />. Export it. (Assume all components are imported.)

Starter code

App.jsx
// Write the App component here

Sample solution

App.jsx
function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If URL is /about, which component renders?

  • Home
  • Contact
  • About Correct answer
  • NotFound

Explanation: The answer: About.

2 Route props

Question
Route's two core props: path and ____.
Answer
Route's two core props: path and element.

Explanation: element prop takes the component.

3 Match the route definitions

Term Meaning
path URL
element component
* 404
Routes container

All lessons in Intermediate