Read json file in Reactjs in a similar way to what im doing in Angular?

Discussão em 'Angular' iniciado por FranciscoFJM, Outubro 24, 2024.

  1. FranciscoFJM

    FranciscoFJM Guest

    I have a json file in the assets folder of my Angular project. I use it to store generic tooltips and labels, so i dont have to hard code them in my HTML code. First i'll show how i read this json file inside my app.

    An example of what i have inside of it:

    "Tooltips": {
    "Editar": "Editar",
    "Eliminar": "Eliminar",
    "Ver": "Ver",
    "Footer": {
    "Facebook": "Seguinos en Facebook",
    "Twitter": "Seguinos en X",
    "Instagram": "Seguinos en Instagram",
    "Linkedin": "Seguinos en Linkedin",
    "YouTube": "Seguinos en YouTube"
    }
    }


    I have a service that's dedicated to read this json file:

    @Injectable()
    export class ConfigService {
    private _tooltips: ITooltips
    constructor(private http: HttpClient) {
    }

    readData() {
    const promise = this.http
    .get('assets/config.json', { responseType: 'text' }).toPromise();

    promise.then(data => {
    const config = parseJson(data)
    this._tooltips = config['Tooltips']

    })

    return promise
    }

    public get tooltips(): ITooltips {
    return this._tooltips
    }

    interface ITooltips {
    Editar: string,
    Ver: string,
    Eliminar: string,

    Footer: {
    Facebook: string,
    Twitter: string,
    Instagram: string,
    Linkedin: string,
    YouTube: string
    }
    }


    "parseJson" refers to this method, which uses the strip-json-comments library:

    export function parseJson(jsonText: string): any {
    const stripedJson = stripJsonComments(jsonText)
    const json = JSON.parse(stripedJson)

    return json
    }


    code inside the app.module.ts:

    export function initializeApp(config: ConfigService) {
    return () => config.readData()
    }

    @NgModule({
    declarations: [
    ],
    imports: [
    ],

    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    providers: [
    ConfigService,
    {
    provide: APP_INITIALIZER,
    useFactory: initializeApp,
    deps: [ConfigService],
    multi: true,
    }

    ],
    bootstrap: [AppComponent]
    })


    All of this makes it so i can inject the ConfigService service inside any of my components and read the config.json file, which is very convenient in my opinion.

    Now, im about to start a new Reactjs project in my job. I have little to no experience in Reactjs, we're gonna have a ton of training first, but i was thinking about this specific part of my Angular app.

    I would like to "translate" this code from Angular to Reactjs. I wanna be able to map a json file to one or multiple Interfaces in something similar to an Angular service, so i can inject it an read the file from anywhere in my Reactjs app. How can i do this? What libraries do you recommend?

    Continue reading...

Compartilhe esta Página