0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you soo much, in this case it won't shows any error but all I want is to show the error on the screen so we can handle the error in production. I think error-boundaries package will help.
0

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

1 Comment

Thank you soo much. Letme try the package, If I need help I will ping you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.