Complete the code to catch runtime errors in a React component using try-catch.
function Example() {
try {
const result = riskyOperation();
return <div>{result}</div>;
} catch ([1]) {
return <div>Error occurred</div>;
}
}The catch block receives the error object, commonly named error or e. Here, error is the correct variable name.
Complete the code to display an error message when a runtime error occurs in a React component.
function ErrorMessage({ error }) {
return <div role="alert">{ [1] }</div>;
}To show the error message, use error.message which contains the error description.
Fix the error in the React error boundary component by completing the missing lifecycle method name.
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static [1](error) { return { hasError: true }; } render() { if (this.state.hasError) { return <h1>Something went wrong.</h1>; } return this.props.children; } }
getDerivedStateFromError is the static lifecycle method used in error boundaries to update state when an error occurs.
Fill both blanks to correctly log error details in the error boundary's lifecycle method.
class ErrorBoundary extends React.Component { componentDidCatch([1], [2]) { console.error([1], [2]); } render() { return this.props.children; } }
The componentDidCatch method receives two parameters: error and info. These provide error details and component stack info.
Fill all three blanks to create a functional component that catches errors using React hooks and displays a fallback UI.
import React, { useState, useEffect } from 'react'; function ErrorCatcher({ children }) { const [hasError, [1]] = useState(false); useEffect(() => { const handleError = () => [2](true); window.addEventListener('error', handleError); return () => window.removeEventListener('error', handleError); }, []); if ([3]) { return <div role="alert">An unexpected error occurred.</div>; } return children; }
We use useState to track error state with hasError and its setter setHasError. The effect listens for errors and sets the error state. The component renders fallback UI if hasError is true.