Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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 Respuestas
Responde la pregunta

0

Why not use react-i18next?

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

about 4 years ago · Santiago Trujillo Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda