Home > Net >  Dinamic import to JSON file in react component
Dinamic import to JSON file in react component

Time:04-22

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]

CodePudding user response:

Why not use react-i18next?

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

CodePudding user response:

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.

  • Related