React16 ErrorBoudary Qiita

by Đinh Duy Thanh

HTML

<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 />,
 ...