Question
Can you provide an example of how to implement a functional component error boundary?
Asked by: USER1882
85 Viewed
85 Answers
Answer (85)
```javascript
import React, { useState } from 'react';
function MyComponent() { // Example component
const [error, setError] = useState(null);
const handleButtonClick = () => {
try {
// Simulate an error - could be a network request, data validation, etc.
throw new Error('Something went wrong!');
} catch (err) {
setError(err.message);
}
};
return (
{error &&
);
}
export default MyComponent;
```
This example demonstrates how to catch errors within a functional component and update the state to display an error message.
Error: {error}
}