Skip to content Skip to sidebar Skip to footer

How To Load External Js File In React?

I have a data.js file with the following structure: var DATA= { 'groups': [{ 'id': '1', 'name': 'group 1', 'subgroups': [{}, {}, ...] }, ...], ... } Is it possib

Solution 1:

Assuming:

  • The data.js file is available during build time
  • File has content in pre-defined format
  • You are using webpack to bundle your application(Optional)

You can use webpack raw-loader(Other bundlers probably have alternatives) to load the content of the file and then parse the content to get the required data.

Example 👇

Edit 1o92xyn41q

Solution 2:

You can definitely use export in .js file. export default or module.exports should work. If you aren't using a language transformer then use the later approach.

varDATA= {
  "groups": [{
    "id": "1",
    "name": "group 1",
    "subgroups": [{}, {}, ...]
  }, ...],
  ...
}

module.exports = DATA;

Otherwise convert the file into json format and directly use it.

{
  "groups": [{
    "id": "1",
    "name": "group 1",
    "subgroups": [{}, {}, ...]
  }, ...],
  ...
}

React app file.js:

import data from'./data.json';

// do something with data.groups

Solution 3:

As I understand it, you just have a file with this exact structure and are looking for a way to access it in your app. Since it uses a var declaration, you can just include it in your web app via a <script> tag and DATA variable will be globally available in your code. If you use TypeScript or FlowType, you should also provide a declaration file with declare var DATA: Data; where Data would be your custom interface describing the structure of this data object. What I would suggest instead, though, is creating a single module that will consume the variable, provide a declaration in this module only, transform it however I like and export it from there. Just to give you an idea what it would look like:

interfaceData {
    groups: Group[];
}

interfaceGroup {
    id: string;
    name: string;
    subgroups: {}[];  // you might provide more type information here, but to begin it would do as well
}

declarevarDATA: Data;

constAPP_DATA: Data = DATA;
exportdefaultAPP_DATA;

Post a Comment for "How To Load External Js File In React?"