简体   繁体   中英

Conditional import timeago languages in React.js

I have a multilingual reactjs app, i need to conditionaly import the used language (declared in the html and used as props, for example if i declare data-locale="nl" i need to import the dutchStrings) i have tried the if condition but it's not working because you can't do it to import files/packages!

import TimeAgo from 'react-timeago';
if (locale === 'en') {
  import englishStrings from 'react-timeago/lib/language-strings/en';
} else if (locale === 'nl') {
  import dutchStrings from 'react-timeago/lib/language-strings/nl';
} else {
  import frenchStrings from 'react-timeago/lib/language-strings/fr';
}
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter';

The declared language should be in the buildFormatter so i can use it in my JSX, i have this switch condition to choose the right Strings

const locale = root_el.getAttribute("data-locale");

let langStrings;
switch(locale) {
  case 'en': {
    langStrings = englishStrings;
    break;
  }
  case 'nl': {
    langStrings = dutchStrings;
    break;
  }
  default:
    langStrings = frenchStrings;
}
const formatter = buildFormatter(langStrings);

Any sugestions/hints on how to do this correctly?

You could use lazy loading to import components/modules conditionally, lazy loading also is a good step in performance improvements. But in order to use it, you'd have to assign it to a variable/constant so that it is recognizable outside the scope of its block.
You could try doing something like this:

import TimeAgo from 'react-timeago';
import React from 'react';
let langString;
if (locale === 'en') {
  langString = React.lazy(()=>import('react-timeago/lib/language-strings/en'));
} else if (locale === 'nl') {
  langString = React.lazy(()=> import('react-timeago/lib/language-strings/nl'));
} else {
  langString = React.lazy(()=>import('react-timeago/lib/language-strings/fr'));
}

Depending on the condition, an appropriate module is loaded into the langString variable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM