@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.
// ## config.js ##..module.exports={endpoint:process.env.API_URL,};// ## myComponent.js ##import{endpoint}from'./config';// Now you could do:constMyComponent=()=><h1>{config.API_URL}</h1>;// Instead of:constMyComponent=()=><h1>{process.env.API_URL}</h1>;
There are different approaches to achieve the above:
If you use CRA (create-react-app), you might want to read this which comes with a nice way out of the box.
Otherwise, you can go through the standard ways using webpack which allows you to do it either with:
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
@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