Guest User

Untitled

a guest
Oct 17th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. import React, {Component} from 'react';
  2. import PropTypes from 'prop-types';
  3. import { connect } from 'react-redux';
  4.  
  5. const withTranslations = (config) => (RawComponent) => {
  6. const mapStateToProps = (state) => ({
  7. languageId: state.currentLanguage.id,
  8. });
  9.  
  10. @connect(mapStateToProps)
  11. class TranslatedComponent extends Component {
  12. static get propTypes() {
  13. return {
  14. languageId: PropTypes.number.isRequired,
  15. };
  16. }
  17.  
  18. _translateDataByField = (key, field) => {
  19. const data = this.props[key][field];
  20. const isSelectBoxValue = typeof data === 'object' && Array.isArray(data.name);
  21.  
  22. if(isSelectBoxValue) {
  23.  
  24. return {
  25. ...data,
  26. name: data.name.reduce((acc, item) => ({
  27. ...acc,
  28. [`_${item.langId}`]: item.value,
  29. }), {})
  30. };
  31.  
  32. } else {
  33.  
  34. return data.reduce((acc, item) => ({
  35. ...acc,
  36. [`_${item.langId}`]: item.value,
  37. }), {});
  38.  
  39. }
  40. };
  41.  
  42. _translateFieldsByKey = (key) => {
  43. return config[key].reduce((acc, item) => ({
  44. ...acc,
  45. [item]: this._translateDataByField(key, item)
  46. }), {});
  47. };
  48.  
  49. _translateProps = (props) => {
  50. const propKeys = Array.isArray(config) ? ['data'] : Object.keys(config);
  51. let translatedProps = {};
  52.  
  53. propKeys.forEach((key) => {
  54. translatedProps = {
  55. ...props,
  56. [key]: this._translateFieldsByKey(key)
  57. }
  58. });
  59.  
  60. return translatedProps;
  61. };
  62.  
  63. render() {
  64. return (
  65. <RawComponent
  66. {...this._translateProps(this.props)}
  67. />
  68. );
  69. }
  70. }
  71.  
  72. return TranslatedComponent;
  73. };
  74.  
  75. export default withTranslations;
Add Comment
Please, Sign In to add comment