← All React exercises

React quiz · 30

Error Boundary Once More

StatusNot taken

Question

What does the code snippet to the right output by console.log? This quiz is updated to React@ 18.3.1 from Jul 2024.

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