I have this enum
defined in our codebase.
enum EventDesc {
EVENT1 = 'event 1',
EVENT2 = 'event 2',
EVENT3 = 'event 3'
}
EVENT1
, EVENT2
, EVENT3
are the event types defined on the backend. And event 1
, event 2
, event 3
are the event descriptions that get rendered on the UI, for some reason they are not defined on the backend. I used an enum
to make the mapping here and to get the corresponding event description.
However now we are supporting internationalization using react-i18next
, meaning that the descriptions have to be translated for a number of languages. In other words they cannot be hardcoded like this only using English.
Our current approach for injecting translation texts is that we have a json file defined for every language we care about and we use them with react-i18next
like this
import {useTranslation} from 'react-i18next';
export const Page = () => {
const {i: i18n } = useTranslation()
return (
<div>{i18n("siteTitle")}</div>
)
}
So before I am getting the event description by just look up the key in the enum
, eg EventDesc[eventType]
. Now obviously it won't work with react-i18next
. I wonder is there a way to parameterize the enum's value using Generics so we can do something like this EventDesc<'en'>[eventType]
or EventDesc<'jp'>[eventType]
. But then I realized even with this it might not work because with enum
we are always defining the event description at compiler time and react-i18next
would only pick up the translation text from the json
files during runtime.
Is there a better alternative than using an enum
to store the event description data?
Using this approach, you can force translations to be maintained - missing translations in the matrix show as compiler errors against an instance of GlobalDictionary.
The global dictionary could be maintained in a single const, but I've shown how you could separate translations - eg to keep them in separate files.
In VSCode save this file as .ts and try adding an event or a language and following through the compiler errors until the translations are complete again.
namespace Internationalization {
type Event = 'event 1' | 'event 2' | 'event 3';
type Language = 'en' | 'jp' | 'fr'
type Translation<L extends Language> = {
[K in Event]: string
}
type GlobalDictionary = {
[L in Language]: Translation<L>
}
const frenchDictionary: Translation<'fr'> = {
"event 1": 'hoh',
"event 2": 'hi',
"event 3": 'hoh',
}
const babel: GlobalDictionary = {
en: {
"event 1": 'yo',
"event 2": 'hi',
"event 3": 'ug',
},
jp: {
"event 1": 'um',
"event 2": 'er',
"event 3": 'ah',
},
fr: frenchDictionary
}
}
In my opinion, trying to parameterize an enum is not the way to work in Angular or React.
Most of the time we want to show the enums as a select DOM element in html, but the words are expected to be translated.
This is one approach to display a gender enum as a select element only in english, no translation at all.
What user sees
import logo from './logo.svg';
import './App.css';
import React from 'react';
function getLengthEnum(ENUMERATION:any):number{
let l_items : any[] = Object.values(ENUMERATION).filter((item) => !isNaN(Number(item)));
return l_items.length;
}
enum Gender{
'None',
'Male',
'Female'
}
export interface MyAplicacionState {
i_genderSelected : number
}
class MyAplicacion extends React.Component<{},MyAplicacionState> {
private li_indexesGenders : number[];
constructor() {
super({});
let i_numGenders : number = getLengthEnum(Gender);
this.li_indexesGenders = Array.from(Array(i_numGenders).keys());//[...Array(i_numGenders).keys()];
this.handleChangeGender = this.handleChangeGender.bind(this);
this.state = {
i_genderSelected : 0
};
}
handleChangeGender(event:any) : void {
this.setState({i_genderSelected: event.target.value});
}
render(){
const listOptionsGender = this.li_indexesGenders.map((i_index:number) =>
<option value={i_index}>{Gender[i_index]}</option>
);
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<select value={this.state.i_genderSelected} onChange={this.handleChangeGender}>
{listOptionsGender}
</select>
</header>
</div>
);
}
}
export default MyAplicacion;
This is one approach to display a gender enum as a select element using react-i18next.
What user sees
import logo from './logo.svg';
import './App.css';
import React from 'react';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
const resTrans = {
de: {
translation: {
'None': 'Keine',
'Male': 'Männlich',
'Female': 'Weiblich'
}
},
fr: {
translation: {
'None': 'Aucun',
'Male': 'Homme',
'Female': 'Femme'
}
}
};
i18n.use(initReactI18next).init({
resources: resTrans,
lng: 'de',
fallbackLng: 'de',
interpolation: {
escapeValue: false
}
});
function getLengthEnum(ENUMERATION:any):number{
let l_items : any[] = Object.values(ENUMERATION).filter((item) => !isNaN(Number(item)));
return l_items.length;
}
enum Gender{
'None',
'Male',
'Female'
}
export interface MyAplicacionState {
i_genderSelected : number,
i_langSelected : number,
ls_gendersTranslated : string[]
}
class MyAplicacion extends React.Component<{},MyAplicacionState> {
private li_indexesGenders : number[];
constructor() {
super({});
let i_numGenders : number = getLengthEnum(Gender);
this.li_indexesGenders = Array.from(Array(i_numGenders).keys());//[...Array(i_numGenders).keys()];
this.handleChangeGender = this.handleChangeGender.bind(this);
this.handleChangeLang = this.handleChangeLang.bind(this);
this.getListGendersTranslated = this.getListGendersTranslated.bind(this);
this.state = {
i_genderSelected : 0,
i_langSelected : 0,
ls_gendersTranslated : this.getListGendersTranslated()
};
}
handleChangeGender(event:any) : void {
this.setState({i_genderSelected: event.target.value});
}
handleChangeLang(event:any) : void {
let i_indexLang : number = parseInt(event.target.value);
let s_lang : string = 'de';
if(i_indexLang===1)s_lang = 'fr';
i18n.changeLanguage(s_lang);
this.setState({i_langSelected: i_indexLang, ls_gendersTranslated : this.getListGendersTranslated()});
}
//from enum list to string list
getListGendersTranslated() : string[]{
let ls_gendersTranslated1 : string[] = [];
this.li_indexesGenders.forEach((i_index : number)=>{
ls_gendersTranslated1.push(i18n.t(Gender[i_index]));
});
return ls_gendersTranslated1;
}
render(){
const listOptionsGender = this.li_indexesGenders.map((i_index:number) =>
<option value={i_index}>{this.state.ls_gendersTranslated[i_index]}</option>
);
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<select value={this.state.i_genderSelected} onChange={this.handleChangeGender}>
{listOptionsGender}
</select>
<select value={this.state.i_langSelected} onChange={this.handleChangeLang}>
<option value={0}>Deutsche</option>
<option value={1}>Française</option>
</select>
</header>
</div>
);
}
}
export default MyAplicacion;
ls_gendersTranslated
is the list of genders(strings) in the language selected.
ls_gendersTranslated
is inside the state so it changes whenever the language selected changes.
using li_indexesGenders
and getListGendersTranslated
you can show enum as a select.
resTrans
, getLengthEnum
and Gender
enum should be in other ts and json files.
Excuse me about this weird notation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.