Instantly share code, notes, and snippets.

Embed
What would you like to do?
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