1

I am integrating a third-party library into my React app. They provide this script I need to add to my <head>:

index.html

<head>
    <script>
      var externalVariable1 = externalVariable1 || {};
      var externalVariable2 = externalVariable2 || {};
    </script>
    // tag.min.js gives value to these variables
    <script async src="//example.com/tag.min.js"></script>
</head>

I need to use access these two variables from my component. I tried the following but I get 'externalVariable1' is not defined error. Any thoughts?

MyScreen.js

import React from 'react';

const MyScreen = () => {
    
    return (
        <React.Fragment>
            <div>
                <h2>Hello!</h2>
            </div>
    
            <div id='myId'>
                {externalVariable.push(function() { externalVariable2.display();})}
            </div>
        </React.Fragment>
    );

}

export default MyScreen;

1 Answer 1

3

If you want to access variables defined in the global scope from inside of a React component, you can typically do that by accessing the variable through the window object.

See the example below:

function App(){
  return <h1>The secret is {window.secret}</h1>
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<!-- Adding some global variables outside of React -->
<script>
var secret = "hello";
</script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.