Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
Conditional lazy loading 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? do i need the switch condition?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda