Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a external JSON config file in react jsx

I want to have a external configuration file (JSON) in my React based project. That is the ultimate outcome or when I deliver it (public folder and the bundle.js) my configuration file also should be given. The User should be able to change the configurations according to his or her wish and use my app. That is there without recompiling my code one should be able to use it. In other words configuration file should not bundle with my app.

like image 843
JEJC_JACALK Avatar asked Jan 25 '18 02:01

JEJC_JACALK


People also ask

How do you load config file in React?

Using WebpackIn your webpack. config. js file, add an externals options and set its value to an object containing the config data. Then in your JavaScript file, access the ConfigData object by importing it as an external module.


1 Answers

The accepted answer may work. However, why make it so complicated?

Step#1. Create a file Config.js, with content

var Configs = {
    prop1 = "abc",
    prop2 = "123"
}

Step#2. Load the file in index.html via script tag.

<div id='root'></div>
<script src="Config.js"></script>
<script src="dist/bundle.js"></script></body>

Step#3. Just access the setting directly within any React component.

class MyComponent extents Component {

    render() {
        //you can access it here if you want
        let myprop1 = window.Configs.prop1;

        return(){
            <div>myprop2 is: {window.Configs.prop2}</div>       
        }
    }
} 

Step#4. Profit?

Does not require or need to involve webpack, webpack-externals, webpack-config, import Config from 'config', or any other BS.

Why it works? because we declared 'Configs' to be a prop of the window object, and loaded it globally.

like image 78
joedotnot Avatar answered Sep 21 '22 19:09

joedotnot