Reputation: 2041
I have hundreds of small .json files in a directory that, for reasons of size, I can't load into memory all at once. Accordingly, I would like to load each .json file individually when it is selected in the UI after the component has mounted. So my question is simple: is there a way to dynamically import those JSON files one at a time, on the fly?
To Summarize:
import '../myData/file1.json
...
import '../myData/file1000.json
won't work because I'd have to type that out hundreds of times, and the end result would probably be too large. Still, I would curious to know if you can recursively import a directory of files into a React app.
I'm hoping that there's a solution like:
fetch('../myData/${fileNumber}.json').then(() => ...
that would allow me to specify which exact file I'd like to load, but from what I've seen it's unclear this is possible.
Upvotes: 0
Views: 2602
Reputation: 2104
Yes you can achieve that in reactjs. This works while in dev mode. To make it work in production you would probably need to change the path for jsons.
Follow this steps:
1) create a folder myData into the public folder : App/public/
2) put there all your json files
3) In your component use it this way:
import React from 'react'
export default props => {
const [file, setFile] = React.useState(1)
React.useEffect(() => {
fetch('/myData/' + file + '.json', {mode: 'no-cors'})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
},[file])
return (
<div>
<div onClick={() => setFile(1)}>file 1</div>
<div onClick={() => setFile(2)}>file 2</div>
<div onClick={() => setFile(3)}>file 3</div>
</div>
)
}
Upvotes: 4