← All React exercises

React quiz · 20

Error Boundary

StatusNot taken

Question

What does the code snippet to the right output by console.log?

Code

exercise.tsx
1// This is a React Quiz from BFE.dev
2
3import * as React from 'react';
4import {Component} from 'react';
5import {createRoot} from 'react-dom/client';
6
7function renderWithError() {
8  throw new Error('error');
9}
10
11function A() {
12  return <ErrorBoundary name="boundary-2">{renderWithError()}</ErrorBoundary>;
13}
14
15function App() {
16  return (
17    <ErrorBoundary name="boundary-1">
18      <A />
19    </ErrorBoundary>
20  )
21}
22
23
24class ErrorBoundary extends Component<
25  { name: string; children: React.ReactNode },
26  { hasError: boolean }
27> {
28  constructor(props) {
29    super(props);
30    this.state = { hasError: false };
31  }
32
33  static getDerivedStateFromError() {
34    return { hasError: true };
35  }
36
37  componentDidCatch() {
38    console.log(this.props.name);
39  }
40
41  render() {
42    if (this.state.hasError) {
43      return <h1>Something went wrong.</h1>;
44    }
45
46    return this.props.children;
47  }
48}
49
50const root = createRoot(document.getElementById("root"));
51root.render(<App />);