0
0
Reactframework~30 mins

Error boundaries concept in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Boundaries Concept in React
📖 Scenario: You are building a React app that shows user profiles. Sometimes, a profile component might crash due to unexpected data. To keep the app running smoothly, you want to catch these errors and show a friendly message instead of a broken screen.
🎯 Goal: Create a React app with an error boundary component that catches errors from a child component and displays a fallback UI.
📋 What You'll Learn
Create a functional component called UserProfile that throws an error when the user prop is null.
Create an error boundary component called ErrorBoundary using a class component with componentDidCatch and getDerivedStateFromError.
Use the ErrorBoundary component to wrap UserProfile in the main App component.
Display a fallback UI message inside ErrorBoundary when an error occurs.
💡 Why This Matters
🌍 Real World
Error boundaries help keep React apps running smoothly by catching unexpected errors in parts of the UI and showing friendly messages instead of broken screens.
💼 Career
Understanding error boundaries is important for React developers to build resilient user interfaces and improve user experience by handling errors gracefully.
Progress0 / 4 steps
1
Create the UserProfile component
Create a functional React component called UserProfile that accepts a user prop. If user is null, throw a new Error with the message 'User data is missing'. Otherwise, return a div that displays User: {user.name}.
React
Need a hint?

Use a simple if check inside the function to throw an error when user is null.

2
Create the ErrorBoundary class component
Create a class component called ErrorBoundary that extends React.Component. Add a state with hasError set to false. Implement the static method getDerivedStateFromError(error) to set hasError to true. Also implement componentDidCatch(error, info) to log the error to the console. In the render method, if hasError is true, return a div with the text 'Something went wrong.'. Otherwise, return this.props.children.
React
Need a hint?

Remember to set initial state in the constructor and update state in getDerivedStateFromError. Use componentDidCatch to log errors.

3
Use ErrorBoundary to wrap UserProfile in App
Create a functional component called App. Inside it, create a constant user set to null. Return JSX where ErrorBoundary wraps UserProfile with the user prop passed in.
React
Need a hint?

Wrap UserProfile inside ErrorBoundary in the returned JSX of App.

4
Export the App component as default
Add a line to export the App component as the default export of the module.
React
Need a hint?

Use export default App; at the end of the file.