4

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?

2
  • According to Reach Router docs the url params should be available as props? so in theory you should have a props.id available inside your Article? Commented Aug 25, 2019 at 5:04
  • yes. I can get the id from props. But how to import json inside a constructor? Commented Aug 25, 2019 at 5:37

2 Answers 2

9

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?

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is what i want. I will share my comment after finishing the job.
Hi @Mahesh just wondering if this worked out for you in the end?
-3

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.