Last active
September 27, 2017 09:04
-
-
Save victorhqc/7b4bfc20a0190f60fa4dd5f78b39b7bc to your computer and use it in GitHub Desktop.
Dynamic render example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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