CustomErrors.jsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. export default class CustomErrors extends Component {
  4. static propTypes = {
  5. onRef: PropTypes.func,
  6. };
  7. static defaultProps = {
  8. onRef: () => {},
  9. };
  10. constructor() {
  11. super();
  12. this.state = {
  13. errors: [],
  14. };
  15. }
  16. componentDidMount() {
  17. this.props.onRef(this);
  18. }
  19. componentWillUnmount() {
  20. this.props.onRef(null);
  21. }
  22. clearErrors = (cb = () => {}) => {
  23. this.setState({
  24. errors: [],
  25. }, cb);
  26. };
  27. addError = (error) => {
  28. // TODO add error parsing, e.g. for arrays/objects
  29. this.setState({
  30. errors: this.state.errors.concat([error]),
  31. });
  32. };
  33. clearAddError = (error) => {
  34. this.setState({
  35. errors: [error],
  36. });
  37. };
  38. listErrors = () => {
  39. let errors = this.state.errors;
  40. let key = 0;
  41. if (errors.length > 0) {
  42. errors = errors.map((error) => {
  43. key++;
  44. return (<li key={ key }>{ error }</li>);
  45. });
  46. return (
  47. <div className="errors">
  48. <p>Something went wrong</p>
  49. <ul>
  50. { errors }
  51. </ul>
  52. </div>
  53. );
  54. } return null;
  55. };
  56. render() {
  57. return this.listErrors();
  58. }
  59. }