0

Recently I am studying ReactJS.

I want to set a global configuration variable such as SERVER_IP_ADDR.

So, when I ask the server for an API (get / post) as Ajax,

I would like to use this global configuration variable in ReactJS.

I usually create a global variable in JavaScript,

Just import it and use it anywhere.

/js/config.js

var SERVER_IP_ADDR

/js/main.js

<script src="/js.config.js"></script>

and like this

<script>
  function request() {
    url = SERVER_IP_ADDR;
  }

</script>

Can not I set up this structure in ReactJS?

Hoony B
  • 115
  • 1
  • 8
  • While it is possible to do what you are looking to do, I suggest you look into [dotenv](https://www.npmjs.com/package/dotenv) and [this question](https://stackoverflow.com/questions/42182577/is-it-possible-to-use-dotenv-in-a-react-project) on how to use dotenv environment variables in a react project. If you are using `create-react-app` then you can also check [here](https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables) – apokryfos Jan 21 '19 at 09:13

3 Answers3

2

You could export a configuration object and import it wherever you need it.

js.config.js

const config = {
  SERVER_IP_ADDR: '...',
  OTHER_CONFIG_KEY: '...'
}

export default config;

and in the file you need it

import configuration from "./js.config"

function request(){
   fetch( configuration.SERVER_IP_ADDR );
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

If you use create-react-app, You should use .env variables for such thing.

  1. Add .env file in your root path, file content would be like this: REACT_APP_SERVER_IP_ADDR=http://myapi.com REACT_APP_CUSTOM_VARIABLE=foobar

  2. then in your source code, you can use it like this: ${process.env.REACT_APP_SERVER_IP_ADDR}/v1/user

More info regarding .env: .env

Alvin Theodora
  • 936
  • 1
  • 11
  • 18
0

yes you can , you can use the config.js file and use it multiple places.

your config.js file looks like

module.exports={
  url : 'api.xxx.com'
}

and you can import it like

import config from './config';

config.url
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70