CodeBlanks Logo Icon CodeBlanks

Fallback UI

Learn to write the fallback UI shown on error.

Fallback UI

The UI shown to the user when an error is caught is called the fallback UI. It can be a simple message or include a 'try again' button.

The fallback offers a gentle explanation, not technical details. Phrases like 'Something went wrong' are common. A support link may be added if needed.

A 'try again' button resets state and re-renders; this helps with transient errors.

Fallback UI design

A good fallback UI offers three things: what happened (short message), what to do (try again or go home) and a support link if needed. Not leaving the user alone matters.

In large apps the fallback is regional: a header error shows in the header bar, a sidebar error in the sidebar. The rest of the app keeps working.

Debug info is shown only in development; it is hidden in production.

Practice Fallback UI with button

Complete the skeleton below. Write an ErrorBoundary class; if hasError is true return <h1>Error</h1> and <button onClick={() => this.setState({ hasError: false })}>Try again</button>, otherwise this.props.children. Export it.

Starter code

App.jsx
import { Component } from "react";

// Write the ErrorBoundary class here

Sample solution

App.jsx
import { Component } from "react";

class ErrorBoundary extends Component {
  state = { hasError: false };
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return (
        <div>
          <h1>Error</h1>
          <button onClick={() => this.setState({ hasError: false })}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

Questions and answers

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

1 What does the fallback UI show?

  • Kod listesi
  • The error stack
  • Teknik detay
  • Nazik mesaj Correct answer

Explanation: The fallback UI shows a gentle message.

2 Try again button

Question
<button onClick={() => this.setState({ hasError: ____ })}>Tekrar dene</button>
Answer
<button onClick={() => this.setState({ hasError: false })}>Tekrar dene</button>

Explanation: Setting hasError to false re-renders.

3 Fallback UI: match the terms

Term Meaning
Fallback UI Friendly message
Try again Resets state
hasError Error state
development Shows details

All lessons in Intermediate