Home > Software engineering >  How to display error message if something not found in reactJS
How to display error message if something not found in reactJS

Time:08-03

I'm working on ReactJS project and my requirement is simple. If something went wrong in the project show error message in screen instead of white screen because of the error.

for example:

for(let i=0; i<array.length; i  ){
//something here
}

so in this case let suppose array.length is undefined or null etc show in console its show me an error and the code breaks with white screen. All I want is to handle this kind of rendering error issue on runtime so user can understand there is a bug here etc.

Thank you.

CodePudding user response:

You can make use of a conditional to check that for you! Like this:

// if it returns true, it means that the array has length of 0 or more
    if(array) { 
     alert('The array exists!');
     console.log('The array exists!');

    } else {
    alert('The array does not exist!');
    console.log('The array does not exist!');
    }

You can also check if the array has a length > 0.

CodePudding user response:

Handling errors in your Components

catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

one way is using Error Boundaries React components :

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. read more about it this article

another way is using React-Error-Boundary package :

This component provides a simple and reusable wrapper that you can use to wrap around your components. Any rendering errors in your components hierarchy can then be gracefully handled. read more about this package

  • Related