The URL is dynamic
url/:id/:name (using Reach Router)
url/1/name1
url/2/differnet-link
url/3/another-link
In Article Component, I want to load 1.json if the URL is url/1/name1 or 2.json if the URL ID is 2
import menuArray from '../data/menu.json';
This is how I usually load JSON in ReactJS
class Article extends React.Component {
constructor(props) {
super(props);
if(/* id is available in the menuArray */) {
// I want to load the JSON by id and store it in state
}
}
}
What is the optimal solution to load dynamic JSON file in ReactJS?
Not sure if this is of any use but I recently built a site where I had to dynamically load markdown files for content in the page based on a prop:
const getMarkdown = async (page) => {
const markdownFilePath = `./content/${page}.md`
const markdownFile = await require(`${markdownFilePath}`)
return markdownFile
}
then in my component I would do:
const introText = getMarkdown(page)
and then render {introText}
You could do the same thing with an async require with your json file using the id from your url params?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With