Complete the code to create a class component that can catch errors using an error boundary.
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: [1] }; } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
The getDerivedStateFromError method should return an object that updates the state to indicate an error occurred. Setting hasError to true triggers the fallback UI.
Complete the code to log the error and info when an error is caught in the error boundary.
componentDidCatch(error, info) {
[1](error, info);
}The componentDidCatch lifecycle method is used to log errors. Using console.error helps to clearly mark error logs in the console.
Fix the error in the code by completing the render method to show fallback UI when an error occurs.
render() {
if (this.state.[1]) {
return <h2>Oops! Something went wrong.</h2>;
}
return this.props.children;
}The state property used to track errors is hasError. Checking this in render allows showing fallback UI.
Fill both blanks to create an error boundary that resets error state when a button is clicked.
class ResettableErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: [1] }; } resetError = () => { this.setState({ hasError: [2] }); }; render() { if (this.state.hasError) { return <> <h1>Error occurred.</h1> <button onClick={this.resetError}>Try again</button> </>; } return this.props.children; } }
When an error happens, hasError is set to true. The resetError method sets it back to false to retry rendering children.
Fill the blanks to create a functional component using React 19+ hooks that manages error state with an error boundary wrapper.
import React, { [1] } from 'react'; function ErrorBoundaryWrapper({ children }) { const [hasError, setHasError] = [2](false); function onError() { setHasError(true); } if (hasError) { return <div>Something went wrong.</div>; } return <ErrorBoundary onError={onError}>{children}</ErrorBoundary>; }
The component uses useState hook to track error state. The first blank imports useState (A), the second blank initializes state with useState(false) (C).