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

89
Visualizações
Dinamic import to JSON file in react component

I am trying to read a json file with a react component. The idea is to be able to choose which file to read based on the default_lang variable. This is the file structure and how I am trying to read them.

./config.json

{
  "enable-lang":{
    "es": "spanish",
    "en": "spanish"
  },
  "default-lang": "en"
}

./dictionary/spanish.json

{
  "title": "Pagina en construccion",
  "description": "Esta página sigue en construcción"
}

./dictionary/english.json

{
  "title": "Page under construction",
  "description": "This page is still under construction"
}

./Language.js

import {Component} from "react";
import config from "./config.json";


export class Language extends Component
{
    static getUsedDictionary() {
        let used_lang = "es";
        let dictionary_path = `./dictionary/${ config["enable-lang"][used_lang] }.json`;
        return import(`${dictionary_path}`);
    }

    static getText (id) {
        let dictionary = this.getUsedDictionary();
        console.log("Dictionary value in getText:" + dictionary);
        console.log("Dictionary[id] value in getText:" + dictionary);
        if(dictionary[id] !== undefined) {
            return dictionary[id];
        } else {
            return dictionary['text-not-found'];
        }
    }
}

dictionary and dictionary[id] value in function getText. I con see this in console

Dictionary value in getText:[object Promise]
Dictionary[id] value in getText:[object Promise]
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Why not use react-i18next?

Or load everthing before and choose which one you'll use

about 4 years ago · Santiago Trujillo Relatório

0

import() returns a Promise so to take that into account, you would have to refactor the code something like this:

import {Component} from "react";
import config from "./config.json";


export class Language extends Component
{
    static getUsedDictionary() {
        let used_lang = "es";
        let dictionary_path = `./dictionary/${ config["enable-lang"][used_lang] }.json`;
        return import(`${dictionary_path}`);
    }

    async static getText (id) {
        let dictionary = await this.getUsedDictionary();
        console.log("Dictionary value in getText:" + dictionary);
        console.log("Dictionary[id] value in getText:" + dictionary);
        if(dictionary[id] !== undefined) {
            return dictionary[id];
        } else {
            return dictionary['text-not-found'];
        }
    }
}

To complete the solution, it would be a good idea to handle possible exceptions coming from getUsedDictionary() as the request can fail. A modern option would be to go with an error boundary or you could do some other type of handling.

Note that you likely have to accommodate your code to deal with asynchronous getText after this change.

about 4 years ago · Santiago Trujillo 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