Start learning free

LESSON 107 OF 161 · FRONTEND: REACT ROUTES AND SHARED STATE

One Crash, Not a Blank Page in JavaScript

Practice

When a component throws an error while it draws, React can't finish the screen. If nothing catches the error, React removes the whole app: the header, the page and the footer. The visitor sees a blank page.

An error boundary catches those errors. It is a class component (hooks can't do this) with a static getDerivedStateFromError() method. React calls it when a child throws, and the object it returns becomes the boundary's new state. Its render() reads this.state and draws a message instead of the children. You can put a boundary around any part of a page, for example just a reviews box:

<ErrorBoundary>
  <ReviewsBox />
</ErrorBoundary>

If ReviewsBox crashes, only the box turns into a message. In this shop, src/Layout.jsx (given) already puts the boundary around the page's Outlet, with key={location.pathname}, so every address gets a fresh boundary. Product 8, the Gift card, has null as its category, so its page crashes on product.category.toUpperCase().

The check must print:

> open /products/7
    section "Product"
      heading 2: Stapler
      link: Next product -> /products/8
> click "Next product"
  request: GET /api/products/8 -> 200
  error: TypeError: Cannot read properties of null (reading 'toUpperCase')
    -   section "Product"
    +   section "Error"
    +     heading 2: Something went wrong
    +     text: This page could not be shown.
    +     link: Back to the shop -> /
> click "Cart (0)"
    +   section "Cart"
    +     heading 2: Cart
    +     text: Your cart is empty

Your task: in src/ErrorBoundary.jsx, give the class a state where hasError is false, a static getDerivedStateFromError method that returns { hasError: true }, and make render return <ErrorMessage /> when this.state.hasError is true.


Assignment
Follow the Coding Tutorial to turn the class in src/ErrorBoundary.jsx into an error boundary: a crashed page shows "Something went wrong" and a link home, and the header stays.


Hint
Setting hasError is not enough on its own: render decides what is drawn. Put the if at the top of render, before return this.props.children;, or the page is drawn again and crashes again.


STEP 1 OF 5
    Ctrl + Enter to check

    Error Boundary in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free