First, create an index.html file where the React application will be rendered:
- Create a new file named index.html
- Add the following HTML code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Catching Errors</title> </head> <body> <div role="main"></div> <script src="./error-boundary.js"></script> </body> </html>
- Save the file
Next, define an error boundary component that will catch errors and render a fallback UI displaying information where the error happened and the error message. Define as well an App component and create a button React element that when clicked will cause the application to fail while setting the state:
- Create a new file named error-boundary.js.
- Import the React and ReactDOM libraries:
import * as React from 'react' import * as ReactDOM from 'react-dom'
- Define an ErrorBoundary component that will display a fallback message when the application fails to render:
class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { hasError: false, message: null, where: null, } } componentDidCatch(error, info) { this.setState({ hasError: true, message: error.message, where: info.componentStack, }) } render() { const { hasError, message, where } = this.state return (hasError ? <details style={{ whiteSpace: 'pre-wrap' }}> <summary>{message}</summary> <p>{where}</p> </details> : this.props.children ) } }
- Define a class component named App that will render a button React element. Once the button is clicked, it will purposely throw an error:
class App extends React.Component { constructor(props) { super(props) this.onClick = this.onClick.bind(this) } onClick() { this.setState(() => { throw new Error('Error while setting state.') }) } render() { return ( <button onClick={this.onClick}> Buggy button! </button> ) } }
- Render the application wrapping the App within the ErrorBoundary component:
ReactDOM.render( <ErrorBoundary> <App /> </ErrorBoundary>, document.querySelector('[role="main"]'), )
- Save the file.