Skip to content

Instantly share code, notes, and snippets.

@victorhqc
Last active September 27, 2017 09:04
Show Gist options
  • Save victorhqc/7b4bfc20a0190f60fa4dd5f78b39b7bc to your computer and use it in GitHub Desktop.
Save victorhqc/7b4bfc20a0190f60fa4dd5f78b39b7bc to your computer and use it in GitHub Desktop.
Dynamic render example
import React, { Component } from 'react';
import reduce from 'lodash/reduce';
const TRANSLATIONS = {
US: {
welcome: 'Welcome {{user}}',
},
MX: {
welcome: 'Bienvenido {{user}}',
},
};
// Translate helper
const translateText = (country = 'US', key, params) => reduce(
params,
(prev, paramValue, paramKey) =>
prev.replace(new RegExp(`{{${paramKey}}}`, 'g'), paramValue),
TRANSLATIONS[country][key]
);
// Curried helper
const translateFromCountry = country => (key, params) =>
translateText(country, key, params);
// Dynamic render component
class Translate extends Component {
translate = (key, params) => {
const {
country,
} = this.props;
return translateFromCountry(country)(key, params);
}
render() {
return this.props.children(this.translate);
}
}
export default class MyComponent extends Component {
render() {
const {
country,
} = this.props;
return (
<div>
<Translate country={country}>
{translate => translate('welcome', { user: 'Victor'})}
</Translate>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment