Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load json dynamically in ReactJS component?

Tags:

reactjs

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?

like image 988
Mahesh Avatar asked Nov 14 '25 14:11

Mahesh


1 Answers

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?

like image 167
Jon B Avatar answered Nov 17 '25 07:11

Jon B