I want to declare a global variable in application where I want to store my API URL and it should accessible for all components
For further actions, you may consider blocking this person and/or reporting abuse
I want to declare a global variable in application where I want to store my API URL and it should accessible for all components
For further actions, you may consider blocking this person and/or reporting abuse
Andrew Baisden -
Ishjot Singh -
Programming In Blood -
Herat Dhruv -
Top comments (3)
@amirsohel007 That's a great question. Btw you should probably tag #beginners and #javascript too. Anyway, since an API URL may vary between environments:
I would advocate the method of setting this variable as an environment variable.
To make it accessible to your different components, you can create a module that deals with both collecting and accessing all the environment variables in the application.
There are different approaches to achieve the above:
.env
file to set environment variables.Note: Add the
.env
file to your.gitignore
.Just in case, you might want to read more about dotenv, cross-env
React supports environment variables out of the box. I feel creating a module just for that is a bit much. You simply need to define the .env file and have
REACT_APP_MYVARIABLE
and react will let you use it anywhere in the app by simply calling:process.env.REACT_APP_MYVARIABLE
Simply use the environment variables it is build for that:
create-react-app.dev/docs/adding-c...
This should be tagged #help