reactjserror-handlingreact-error-boundary

React Js ErrorBoundary only working for the main layout components and not for nested components


I am using errorboundaries in my code and when I use it in the file where I am rendering my main layout components it works, Eg.:

<ErrorBoundary>
<header></header>
</ErrorBoundary>
<ErrorBoundary>
<main/> //this component has an error
</ErrorBoundary>
<ErrorBoundary>
<footer></footer>
</ErrorBoundary>

The above code works and the fallback UI is shown for the error that is in the main component. But when I use errorboundary component inside the main component file it does not work, Eg of errorboundary that does not work:

class main extends React.Component {
//code
<ErrorBoundary>
{object}
</ErrorBoundary>
//more code

This does not work and the whole app crashes instead, displaying only a blank page. Why might this be happening and how to deal with it? Thank you.


Solution

  • I figured it out. Errorboundary catches the error in components. So it wasn't working earlier, but when I rendered a faulty component in between the ErrorBoundary instead, it worked.

    <ErrorBoundary>
    <FaultyComponent/>
    </ErrorBoundary>
    

    it worked.