Q: Error Boundary in React that catches an error and displays a fallback UI

  1. ErrorBoundary Component: This catches errors in its child components and displays a fallback UI (Something went wrong.).
  2. MyComponent: This component intentionally throws an error to demonstrate how the error boundary works.
  3. App Component: Wraps MyComponent with ErrorBoundary to catch and handle errors

 When you run this code, you'll see "Something went wrong." displayed on the screen because MyComponent throws an error, which is caught by the ErrorBoundary

CREATING SAMPLE:

Let's create a simple example of an error boundary in React that catches an error and displays a fallback UI when an error occurs in a component.

1.ErrorBoundary Component

import React, { Component } from "react";
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  componentDidCatch(error, errorInfo) {
     return this.props.fallback;
      // return <h1>Something went wrong.</h1>; without fallback in app.js
    }
  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
export default ErrorBoundary;

2.MyComponent
import React from "react";

const MyComponent = () => {
  throw new Error("This is a simulated error!");
  return <div>This will not be rendered. from MyComponent</div>;
};

export default MyComponent;

3.App.js

Now we wrap MyComponent with the ErrorBoundary to catch errors:

import React from "react";
import ErrorBoundary from "./ErrorBoundary";
import MyComponent from "./MyComponent";

const App = () => {
  return (
    // <ErrorBoundary> without fallback declare in ErrorBoundary.js
    <ErrorBoundary fallback={<>Oh no! Do something!</>}>
      <MyComponent />
    </ErrorBoundary>
  );
};

export default App;


















Comments

Popular posts from this blog

reactjs questions part 4

ReactJS: How and when to force a React component to re-render