cf.completefrontend

Write the codeEasy

Write an ErrorBoundary class with a fallback and a Try again button

Write ErrorBoundary, a class component and the file's named export. When a component inside it throws while rendering or in an Effect, it shows a fallback in place of all its children: an element with role="alert" that says Something went wrong: followed by the error's message, and a Try again button.

Try again clears the error and renders the children again; if they throw again, the fallback comes back. Two optional props: onError(error, info) is called once for each error caught, with the info React gives (its componentStack says where the error came from), and onReset() is called when Try again is pressed.

<ErrorBoundary onError={(error, info) => report(error, info.componentStack)}>
  <TeaCard tea={tea} />
</ErrorBoundary>
 
// When TeaCard throws new Error("No notes for this tea."):
// Something went wrong: No notes for this tea.
// [Try again]
Write this (App.jsx)
import { Component } from "react";
 
export class ErrorBoundary extends Component {
  // Catch errors from the children, show the fallback, and reset on Try again.
  render() {
    return this.props.children;
  }
}
The checks your code must pass
  • renders its children when nothing throws
  • shows the error's message and Try again when a child throws
  • catches an error thrown in a child's Effect
  • Try again renders the children again
  • shows the fallback again when the children throw again
  • calls onError once per caught error, with the component stack
  • calls onReset when Try again is pressed

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…