Skip to content

Commit

Permalink
🥅 Error Boundary
Browse files Browse the repository at this point in the history
Error Boundary
  • Loading branch information
SaishJ committed Sep 11, 2022
1 parent 89a9384 commit 83c11fa
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,5 @@ export default ClassClick;
### [Refs with Class Component](https://github.com/SaishJ/React-JS-Beginner-to-Advanced/commit/6eb606c14741e6397a9a91a0cf0d5cfb20e1163c)

### [Forwarding Refs](https://github.com/SaishJ/React-JS-Beginner-to-Advanced/commit/9a57ffbe3d6eeea400c3604bc66fe6bb6bafabdd)

### [Portals](https://github.com/SaishJ/React-JS-Beginner-to-Advanced/commit/89a9384c40963c77ec47ac76cbd8699ee1bebe4d)
13 changes: 12 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,22 @@ import RefDemo2 from "./components/RefDemo2";
import FocusInput from "./components/FocusInput";
import FRParentInput from "./components/FRParentInput";
import PortalDemo from "./components/PortalDemo";
import Hero from "./components/Hero";
import ErrorBoundary from "./components/ErrorBoundary";

function App() {
return (
<div className="App">
<PortalDemo />
<ErrorBoundary>
<Hero heroName="Superman" />
</ErrorBoundary>
<ErrorBoundary>
<Hero heroName="Batman" />
</ErrorBoundary>
<ErrorBoundary>
<Hero heroName="Joker" />
</ErrorBoundary>
{/* <PortalDemo /> */}
{/* <FRParentInput /> */}
{/* <FocusInput /> */}
{/* <RefsDemo /> */}
Expand Down
34 changes: 34 additions & 0 deletions src/components/ErrorBoundary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React, { Component } from "react";

class ErrorBoundary extends 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, info) {
// log the error to an error reporting service
console.log(error);
console.log(info);
}

render() {
if (this.state.hasError) {
// render any custom fallback UI
return <h2>Something went wrong</h2>;
}
return this.props.children;
}
}

export default ErrorBoundary;
10 changes: 10 additions & 0 deletions src/components/Hero.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React from "react";

function Hero({ heroName }) {
if (heroName === "Joker") {
throw new Error("Not a hero!");
}
return <div>{heroName}</div>;
}

export default Hero;

0 comments on commit 83c11fa

Please sign in to comment.