Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!