<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {error: null, errorInfo: null};
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({error, errorInfo})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{whiteSpace: 'pre-wrap'}}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.state = {error: false};
}
deleteItem(){
this.setState({error: true})
}
render(){
const {name, description} = this.props
if (this.state.error) {
// Simulate a JS error
throw new Error('Error');
}
return(
<div>
<strong>{name}</strong>
<button onClick={() => this.deleteItem()}>Delete</button>
</div>
)
}
}
class TodoList extends React.Component {
render(){
return(
<div className="todo-list" style={{background: "#eee", padding: "10px"}}>
{this.props.children}
</div>
)
}
}
function TodoApp() {
return (
<div>
<p>
<b>
React 16のErrorBoundaryの例
<br /><br />
Deleteボタンをクリックしたら、エラー発生する
<br />
</b>
</p>
<hr />
<ErrorBoundary>
<TodoList>
<TodoItem name="todo1"/>
<TodoItem name="todo2"/>
<TodoItem name="todo3"/>
</TodoList>
</ErrorBoundary>
</div>
);
}
ReactDOM.render(
<TodoApp />,
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.