Step 27: 404 Page

What happens when we navigate to a route that we didn't expect? For example, in the demo below, I navigates to the route /blah:

Conventionally, we would want to show a "404 Page" (Read What is a 404 Page and Why Do You Need One?).

Mantine UI has some pre-made pages/components available at https://ui.mantine.dev/. I'm going to copy one of their examples for 404 pages!

Create a file pages/NotFound.jsx with the following content:

import {
  createStyles,
  Title,
  Text,
  Button,
  Container,
  Group,
} from "@mantine/core";
import { Link } from "react-router-dom";

const useStyles = createStyles((theme) => ({
  root: {
    paddingTop: 80,
    paddingBottom: 80,
  },

  label: {
    textAlign: "center",
    fontWeight: 900,
    fontSize: 220,
    lineHeight: 1,
    marginBottom: theme.spacing.xl * 1.5,
    color:
      theme.colorScheme === "dark"
        ? theme.colors.dark[4]
        : theme.colors.gray[2],

    [theme.fn.smallerThan("sm")]: {
      fontSize: 120,
    },
  },

  title: {
    fontFamily: `Greycliff CF, ${theme.fontFamily}`,
    textAlign: "center",
    fontWeight: 900,
    fontSize: 38,

    [theme.fn.smallerThan("sm")]: {
      fontSize: 32,
    },
  },

  description: {
    maxWidth: 500,
    margin: "auto",
    marginTop: theme.spacing.xl,
    marginBottom: theme.spacing.xl * 1.5,
  },
}));

function NotFound() {
  const { classes } = useStyles();

  return (
    <Container className={classes.root}>
      <div className={classes.label}>404</div>
      <Title className={classes.title}>You have found a secret place.</Title>
      <Text
        color="dimmed"
        size="lg"
        align="center"
        className={classes.description}
      >
        Unfortunately, this is only a 404 page. You may have mistyped the
        address, or the page has been moved to another URL.
      </Text>
      <Group position="center">
        <Link to={"/"}>
          <Button variant="subtle" size="md">
            Take me back to home page
          </Button>
        </Link>
      </Group>
    </Container>
  );
}

export default NotFound;

Notice how I used the Link component from react-router library for navigation. This is an alternative to navigate hook!

Next, update the App.jsx file as follows:

  1. Add import NotFound from "./pages/NotFound"; at the top of the file.

  2. Add <Route path="*" element={<NotFound />} /> as the last route before the closing </Routes> tag.

Let's try the /blah route again!