Mahesh
Mahesh

Reputation: 1593

How to load json dynamically in ReactJS component?

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?

Upvotes: 4

Views: 10152

Answers (2)

Jon B
Jon B

Reputation: 2824

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?

Upvotes: 9

Noor Sheikh
Noor Sheikh

Reputation: 1

A better way is to create a .js file and then use const e.g: data.js

const navigation = [
    {
        navItemId: 1,
        navItemName: 'About Me',
        navItemPath: '/'
    }
];
export {navigation};

The file where you want to use it, use the below code:

import { navigation, bio, education } from './constants';
state = {navigation: navigation}

Upvotes: -3

Related Questions