CodeBlanks Logo Icon CodeBlanks

Navigation and 404

Add a go-to-cart button and a 404 page.

Redirect and 404

The last lesson adds the 404 page and redirects legacy paths. Setting the path attribute to an asterisk renders that route when no path matches; the Navigate component is used for programmatic redirects.

To redirect an old path to a new one, use the Navigate component with a to attribute. The replace attribute does not push a new history entry; the back button does not return to the source path.

The 404 page offers the user a gentle way back; linking to the home page is a common approach.

Navigate with replace

The Navigate component can be used as the element of a route. to is the target path, replace decides whether to replace the history entry.

Without replace, the back button returns to the redirect source; this can create a redirect loop. With replace, the back button skips the source.

This pattern moves old URLs to a new structure; the user reaches the right page even when opening old bookmarks.

Practice 404 and redirect

Complete the skeleton below. Write an App component; in Routes add a Route with path="*" and element={"{"<NotFound />}"}, and another with path="old" and element={"{"<Navigate to="/new" replace />}"}. Export it.

Starter code

App.jsx
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";

// Write the App component here

Sample solution

App.jsx
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="*" element={<NotFound />} />
        <Route path="old" element={<Navigate to="/new" replace />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Questions and answers

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

1 How is the 404 route written?

  • path="none"
  • path="*" Correct answer
  • path="?"
  • path="404"

Explanation: path="*" renders when no path matches.

2 Navigate redirect

Question
import { Navigate } from "react-router-dom";

function Old() {
  return <____ to="/new" replace />;
}
Answer
import { Navigate } from "react-router-dom";

function Old() {
  return <Navigate to="/new" replace />;
}

Explanation: Navigate to performs a redirect.

3 Navigation and 404: match the terms

Term Meaning
path="*" 404 path
Navigate Redirect
to Target path
replace Replaces history

All lessons in Intermediate