Search code examples
reactjserror-handlingreact-proptypes

How to throw error instead of warning from proptypes in Reactjs?


We usually get a warning on the console when we have any invalid prop type in reactjs. But I want to display an error to the developer or the user so that it becomes clear and the user needs to fix it on priorty basis. Is there any way to throw an error on the main screen instead of console?

The reason being, in my code there is an array of object that is undefined as it is not passed and i have applied a check in the proptypes but that is appearing in the console. I need some kind of popup so that the user gets a clear image that data is not available.

Instead of the screen below: enter image description here


Solution

  • The official way is to implement an ErrorBoundary, catch the error, and render a specific UI element for it.

    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.

    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    
      static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI.
        return { hasError: true };
      }
    
      componentDidCatch(error, errorInfo) {
        // You can also log the error to an error reporting service
        logErrorToMyService(error, errorInfo);
      }
    
      render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>Something went wrong.</h1>;
        }
    
        return this.props.children; 
      }
    }