I am new on react.js I have implemented one component in which I am fetching the data from server and use it like,
CallEnterprise:function(TenantId){
fetchData('http://xxx.xxx.xx.xx:8090/Enterprises?TenantId='+TenantId+' &format=json').then(function(enterprises)
{
EnterprisePerspectiveActions.getEnterprise(enterprises);
}).catch(function()
{
alert("There was some issue in API Call please contact Admin");
//ComponentAppDispatcher.handleViewAction({
// actionType: MetaItemConstants.RECEIVE_ERROR,
// error: 'There was a problem getting the enterprises'
//});
});
},
I want to store Url in configuration file so when I deployed this on Testing server or on Production I have to just change the url on config file not in js file but I don't know how to use configuration file in react.js
Can anyone please guide me how can I achieve this ?
This question is related to
javascript
reactjs
configuration
webpack
flux
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
process.env.REACT_APP_SERVER_PORT
Actually in case if you have any file that has key value pairs like this:
someKey=someValue
someOtherKey=someOtherValue
You can import that into webpack by a npm module called properties-reader
I found this really helpful since I'm integrating react with Java Spring framework where there is already an application.properties file. This helps me to keep all config together in one place.
"properties-reader": "0.0.16"
const PropertiesReader = require('properties-reader');
const appProperties = PropertiesReader('Path/to/your/properties.file')._properties;
externals: {
'Config': JSON.stringify(appProperties)
}
var Config = require('Config')
fetchData(Config.serverUrl + '/Enterprises/...')
Source: Stackoverflow.com