123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143 |
- import React, { Component } from "react";
- import PropTypes from "prop-types";
- const i18next = require("i18next");
- const t = i18next.t;
- i18next.loadNamespaces("customMessages");
- export default class CustomMessages extends Component {
- static propTypes = {
- onRef: PropTypes.func,
- };
- static defaultProps = {
- onRef: () => {},
- };
- constructor() {
- super();
- this.state = {
- error: [],
- info: [],
- success: [],
- };
- }
- componentDidMount() {
- this.props.onRef(this);
- }
- componentWillUnmount() {
- this.props.onRef(null);
- }
- clearError = (cb = () => {}) => {
- this.clear("error", cb);
- };
- addError = (error) => {
- this.add("error", error);
- };
- clearAddError = (error) => {
- this.clearAdd("error", error);
- };
- clearInfo = (cb = () => {}) => {
- this.clear("info", cb);
- };
- addInfo = (info) => {
- this.add("info", info);
- };
- clearAddInfo = (info) => {
- this.clearAdd("info", info);
- };
- clearSuccess = (cb = () => {}) => {
- this.clear("success", cb);
- };
- addSuccess = (success) => {
- this.add("success", success);
- };
- clearAddSuccess = (success) => {
- this.clearAdd("success", success);
- };
- clearErrorSuccess = (cb) => {
- this.setState({
- error: [],
- success: [],
- }, cb);
- };
- clearAll = (cb) => {
- this.setState({
- error: [],
- success: [],
- info: [],
- }, cb);
- };
- clear = (type, cb) => {
- this.setState({
- [type]: [],
- }, cb);
- };
- add = (type, message) => {
- // TODO add error parsing, e.g. for arrays/objects
- console.log("CM_ADD", type, message, this.state[type]);
- this.setState({
- [type]: this.state[type].concat([message]),
- });
- };
- clearAdd = (type, message) => {
- this.setState({
- [type]: [message],
- });
- };
- list = (type) => {
- let messages = this.state[type];
- let key = 0;
- if (messages.length > 0) {
- messages = messages.map((message) => {
- key++;
- return (<li key={ key }>{ message }</li>);
- });
- let text = "";
- if (type === "error") text = t("customMessages:somethingWentWrong");
- else if (type === "info") text = t("customMessages:info");
- else if (type === "success") text = t("customMessages:success");
- return (
- <div key={ type } className={ `custom-messages custom-messages-${type}` }>
- <p>{ text }</p>
- <ul>
- { messages }
- </ul>
- </div>
- );
- } return null;
- };
- render() {
- if (this.state.error.length > 0 || this.state.info.length > 0 || this.state.success.length) {
- return (
- <div>
- {this.list("error")}
- {this.list("info")}
- {this.list("success")}
- </div>
- );
- } else return null;
- }
- }
|