Using DropConfig can make it easy to add translations for your website and enable you to easily pass off the translation work to other people.
We are going to be using react in this example with DropConfig.
The scenario
We want to be able to pass a translation key to a React component and have the proper translation loaded depending on the user's browser.
<div> | |
<Translation default="Welcome">homepage_welcome</Translation> | |
</div> |
The DropConfig document.
We will want to create a document that has at the top level the language. Then children key value pairs of the translation key and value.
e.g.
{
"en-US": {
"homepage_welcome": "Welcome"
}
}
Why DropConfig?
DropConfig allow you to pass off all the work of translations to other people on your team or in your company.
You just have to give them the URL and they can fill in the data without breaking the JSON!
The React Component
This is a pretty simple component all the hard work will be done in our translation loader and get
-er
import React, {Component} from "react"; | |
import {getTranslation} from "./translator"; | |
class Translate extends Component { | |
render(){ | |
const key = children; | |
const translation = getTranslation(key, this.props.default); | |
return ( | |
<span>{translation}</span> | |
) | |
} | |
} |
The Translation Loader
const configUrl = "https://a.dropconfig.com/1291ea92-845b-46a4-a020-74bf0c5e72f4.json" | |
let translations = null; | |
async function loadTranslations(lang){ | |
const req = await fetch(configUrl); | |
const data = await req.json(); | |
// We will want a better system to find out the language etc. | |
// But this will do for now. | |
translations = data[lang]; | |
} | |
function getTranslation(key, def){ | |
if(!translations || !translations[key]){ | |
return def; | |
} else { | |
return translations[key] | |
} | |
} | |
export { | |
loadTranslations, | |
getTranslation | |
} |
I hope this helps you with translations on your site and seeing the power of DropConfig
Top comments (0)