stackerLoki
stackerLoki

Reputation: 93

How to use global var in react?

I need to use virtual assistant from another source ( and need to use this vars

<script>
        var chat_client = 'big',
            chat_mode=2,
            ailabs_user_id = null,
        ailabs_user_info  = {'user_intent_category_label':'DEFAULT', 'info_fullname':'Ержанов Ануар Толегенович', 'info_iin':'921102350927', 'info_phone_number':'87473096538'};
    </script>

How i can use it in react and do it global var for have a oppurtunity to use it from template? When I try to use var from Header component I have error ( is undefined )
i need to use 'info_fullname':{employee.fullname}

Upvotes: 1

Views: 131

Answers (2)

Aobo Cheng
Aobo Cheng

Reputation: 4528

You can access all global variables with window.variableName, window is the global object in the browser environment.

A better way to work with the global variable is by using it with Webpack external config.

Webpack External Reference

Upvotes: 1

Naresh Kumar
Naresh Kumar

Reputation: 814

Why don't you try using Context?

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

However, please take a note of this as mentioned in docs:

We can create global variable by using window keyword.

window.$name = 'king' //global variable

Now we can access the global variable window.$name from our components.

function App() {
  const name = window.$name;
  console.log(name); // 'king'

  return (
    <div>
      <h1>{name}</h1>
    </div>
  );
}

Upvotes: 1

Related Questions