Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component} from 'react';
- import PropTypes from 'prop-types';
- import { connect } from 'react-redux';
- const withTranslations = (config) => (RawComponent) => {
- const mapStateToProps = (state) => ({
- languageId: state.currentLanguage.id,
- });
- @connect(mapStateToProps)
- class TranslatedComponent extends Component {
- static get propTypes() {
- return {
- languageId: PropTypes.number.isRequired,
- };
- }
- _translateDataByField = (key, field) => {
- const data = this.props[key][field];
- const isSelectBoxValue = typeof data === 'object' && Array.isArray(data.name);
- if(isSelectBoxValue) {
- return {
- ...data,
- name: data.name.reduce((acc, item) => ({
- ...acc,
- [`_${item.langId}`]: item.value,
- }), {})
- };
- } else {
- return data.reduce((acc, item) => ({
- ...acc,
- [`_${item.langId}`]: item.value,
- }), {});
- }
- };
- _translateFieldsByKey = (key) => {
- return config[key].reduce((acc, item) => ({
- ...acc,
- [item]: this._translateDataByField(key, item)
- }), {});
- };
- _translateProps = (props) => {
- const propKeys = Array.isArray(config) ? ['data'] : Object.keys(config);
- let translatedProps = {};
- propKeys.forEach((key) => {
- translatedProps = {
- ...props,
- [key]: this._translateFieldsByKey(key)
- }
- });
- return translatedProps;
- };
- render() {
- return (
- <RawComponent
- {...this._translateProps(this.props)}
- />
- );
- }
- }
- return TranslatedComponent;
- };
- export default withTranslations;
Add Comment
Please, Sign In to add comment