CustomMessages.jsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. export default class CustomMessages extends Component {
  4. static propTypes = {
  5. onRef: PropTypes.func,
  6. };
  7. static defaultProps = {
  8. onRef: () => {},
  9. };
  10. constructor() {
  11. super();
  12. this.state = {
  13. error: [],
  14. info: [],
  15. success: [],
  16. };
  17. }
  18. componentDidMount() {
  19. this.props.onRef(this);
  20. }
  21. componentWillUnmount() {
  22. this.props.onRef(null);
  23. }
  24. clearError = (cb = () => {}) => {
  25. this.clear("error", cb);
  26. };
  27. addError = (error) => {
  28. this.add("errors", error);
  29. };
  30. clearAddError = (error) => {
  31. this.clearAdd("error", error);
  32. };
  33. clearInfo = (cb = () => {}) => {
  34. this.clear("info", cb);
  35. };
  36. addInfo = (info) => {
  37. this.add("info", info);
  38. };
  39. clearAddInfo = (info) => {
  40. this.clearAdd("info", info);
  41. };
  42. clearSuccess = (cb = () => {}) => {
  43. this.clear("success", cb);
  44. };
  45. addSuccess = (success) => {
  46. this.add("success", success);
  47. };
  48. clearAddSuccess = (success) => {
  49. this.clearAdd("success", success);
  50. };
  51. clearErrorSuccess = (cb) => {
  52. this.setState({
  53. error: [],
  54. success: [],
  55. }, cb);
  56. };
  57. clearAll = (cb) => {
  58. this.setState({
  59. error: [],
  60. success: [],
  61. info: [],
  62. }, cb);
  63. };
  64. clear = (type, cb) => {
  65. this.setState({
  66. [type]: [],
  67. }, cb);
  68. };
  69. add = (type, message) => {
  70. // TODO add error parsing, e.g. for arrays/objects
  71. this.setState({
  72. [type]: this.state[type].concat([message]),
  73. });
  74. };
  75. clearAdd = (type, message) => {
  76. this.setState({
  77. [type]: [message],
  78. });
  79. };
  80. list = (type) => {
  81. let messages = this.state[type];
  82. let key = 0;
  83. if (messages.length > 0) {
  84. messages = messages.map((message) => {
  85. key++;
  86. return (<li key={ key }>{ message }</li>);
  87. });
  88. let text = "";
  89. if (type === "error") text = "Something went wrong";
  90. else if (type === "info") text = "Info";
  91. else if (type === "success") text = "Success";
  92. return (
  93. <div key={ type } className={ type }>
  94. <p>{ text }</p>
  95. <ul>
  96. { messages }
  97. </ul>
  98. </div>
  99. );
  100. } return null;
  101. };
  102. render() {
  103. return (
  104. <div>
  105. { this.list("error") }
  106. { this.list("info") }
  107. { this.list("success") }
  108. </div>
  109. );
  110. }
  111. }