Nested Translation Keys and Fallback Chains
What You'll Learn
You'll learn how to organize translations hierarchically and gracefully handle missing translations with fallback strategies.
Why Nest Translation Keys?
As applications grow, flat translation files become unwieldy. Instead of keys like user_profile_edit_button, you can structure translations as nested objects:
{
"user": {
"profile": {
"edit": "Edit Profile",
"save": "Save Changes"
}
}
}
This mirrors your application's component structure and makes translations easier to maintain. Access nested keys with dot notation or bracket syntax: t('user.profile.edit').
Implementing Fallback Chains
Fallback chains prevent broken UI when translations are missing. Think of it like a safety net with multiple layers:
- Specific locale (e.g.,
pt-BR) - Base language (e.g.,
pt) - Default language (e.g.,
en) - Key itself (last resort)
function getTranslation(key, locale) {
// Try pt-BR
let value = translations['pt-BR']?.[key];
if (value) return value;
// Fall back to pt
value = translations['pt']?.[key];
if (value) return value;
// Fall back to en
value = translations['en']?.[key];
if (value) return value;
// Last resort: show key
return key;
}
Combining Both Concepts
Navigate nested objects while falling back through locales:
function resolveNestedKey(obj, path) {
return path.split('.').reduce((current, key) => current?.[key], obj);
}
// Try pt-BR → pt → en for "user.profile.edit"
Key Takeaway: Structure translations as nested objects for maintainability, and implement multi-level fallback chains to ensure users always see meaningful text—even when specific translations are missing.