I
I
Ivan Pavlenko2018-09-26 18:17:57
JavaScript
Ivan Pavlenko, 2018-09-26 18:17:57

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

4 answer(s)
A
Alexander, 2018-09-26
@MrGobus

With webpack:

plugins:[
        new webpack.DefinePlugin({
            GLOBAL_VARIABLE: JSON.stringify('value') 
        }),
]

After building the modules, it is visible throughout the application

A
Alexey Nikolaev, 2018-09-26
@Heian

// globals/index.js
const restApiHost = 1231313;
export { restApiHost };

// component.js
import { restApiHost } from './globals';
console.log(restApiHost);

So?

A
Anton Spirin, 2018-09-26
@rockon404

A good option would be to pass environment dependent variables to webpack.DefinePlugin:

new webpack.DefinePlugin({
  '__HOST__': JSON.stringify('https://example.com')
});

In code:
xhr.open("GET", __HOST__ + `/api/v1.0/items/${first}/${this.state.itemPerPage}`, true);

A
Anton Shvets, 2018-09-27
@Xuxicheta

just like in any script
window.global = {
restApiHost
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question