Answer the question
In order to leave comments, you need to log in
How to make a global variable in REACT?
It would seem a simple question, but, I have no luck with a normal example. In Google, everyone comes from afar and by the time it comes down to it, apparently, they forget what they wrote about, or a piece of code is so large that there is no longer any power to realize it =)
So, in REACT, you need to somehow organize a global variable for passing the RestAPI address of the server to application components. The address is not complex, " localhost ".
And then, inside the component, I would like to use this variable like this:
xhr.open("GET", global.restApiHost + `/api/v1.0/items/${first}/${this.state.itemPerPage}`, true)
Answer the question
In order to leave comments, you need to log in
With webpack:
plugins:[
new webpack.DefinePlugin({
GLOBAL_VARIABLE: JSON.stringify('value')
}),
]
// globals/index.js
const restApiHost = 1231313;
export { restApiHost };
// component.js
import { restApiHost } from './globals';
console.log(restApiHost);
A good option would be to pass environment dependent variables to webpack.DefinePlugin:
new webpack.DefinePlugin({
'__HOST__': JSON.stringify('https://example.com')
});
xhr.open("GET", __HOST__ + `/api/v1.0/items/${first}/${this.state.itemPerPage}`, true);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question