简体   繁体   中英

how to change json file import path in javascript

Hi here is what is working and what i need to change. I have under my SCR folder a data folder for testing purposes in which there are many json files.

I actually have many react list component which I want to change to only one generic component by passing the json filename and path instead of hardcoding it. this works

import React from 'react'
import { Link } from 'react-router-dom'
import * as s from '../../components/Shared/ListCards.styles'

import ListData from '../../data/user.json'

const ListCards = () => {
    const listJSX = ListData.map((user, index) => {
        return ()

I would like to change

import ListData from '../../data/user.json'
to
import ListData from 'path/filename.json'

path and filename is stored in localStorage

localStorage.getItem('colName')

You could use dynamic imports

const { default: ListData } = await import('path/filename.json');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports


You may want to considering using the fetch api instead, if the path stored inside your local storage relates to a URL:

const ListCards = () => {
    const { listData, setListData } = useState([]);
    (async () => {
        const response = await fetch('/urlpath/filename.json')
        const data = await response.json()
        setListData(data)
    })();
    const listJSX = listData.map((user, index) => {
        return ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM