Complete the code to create a class component that catches errors using an error boundary.
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; } }
The getDerivedStateFromError method is a static lifecycle method used in error boundaries to update state when an error occurs.
Complete the code to log error details inside the error boundary.
class ErrorBoundary extends React.Component { componentDidCatch(error, info) { [1](error, info); } render() { return this.props.children; } }
console.error is used to log errors in the console, which helps in debugging.
Fix the error in the error boundary render method to properly display fallback UI.
render() {
if (this.state.hasError) {
return [1];
}
return this.props.children;
}The render method must return valid JSX. Returning a string alone is invalid; wrapping it in a <div> makes it valid JSX.
Fill both blanks to create an error boundary that updates state and logs errors.
class ErrorBoundary extends React.Component { static [1](error) { return { hasError: true }; } [2](error, info) { console.error(error, info); } render() { if (this.state.hasError) { return <h2>Oops! Something went wrong.</h2>; } return this.props.children; } }
getDerivedStateFromError updates the state when an error occurs, and componentDidCatch logs the error details.
Fill the blanks to create a functional component that catches global errors using hooks.
import React, { useState, [1] } from 'react'; function ErrorBoundary({ children }) { const [hasError, setHasError] = useState(false); [2](() => { const handleError = () => setHasError(true); window.addEventListener('error', handleError); return () => window.removeEventListener('error', handleError); }, []); if (hasError) { return <h1>Something went wrong.</h1>; } return children; } export default ErrorBoundary;
useEffect is used to run side effects like adding and cleaning up event listeners in functional components.