How can I pass a variable from 'outside' to a react app?
The EcmaScript 6 introduced block-scope variables and constants declared by let
resp. const
.
In contrast to the "old style" declaration of variable by var
the visibility of such variable resp. constant is limited to actual block.
The scope of constant const1
(resp. const2
) is therefore limited only to the code inside the script tag.
To be able to access the const1
(resp. const2
) from another script tag you would need to change its visibility. This can be achieved either by declaring it by var
or by assigning its value to a variable declared by var
.
E.g.:
<script type="text/javascript">
const const1 = "1234";
const const2 = "5678";
var visibleConst1 = const1;
</script>
Later in your React application you can read it from window.visibleConst1
.
I see two options here.
- Assign the variables to the
window
object - Use environment variables
Using the window
object
To use the window
object, declare the variable as
myVar = 'someString'
or
window.myVar = 'someString'
In both cases you'll access the variable within React with window.myVar
. Here's a quick example:
class App extends React.Component {
render() {
return (
<div>
<h1>Hello, React and ES6!</h1>
<p>Let's play. :)</p>
<p>{window.myVar}</p>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
html,
body {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
font-family: Helvetica Neue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
<script>
window.myVar = 'someString2'
</script>
Using environment variables
The Create React App build allows for environment variables to be used within the app. To add an environment variable create a .env
file in the root of your project, then add the appropriate variables and prefix the variable name with REACT_APP_
. For example:
REACT_APP_MYVAR = "someString"
In the app these variables can be accessed within your components with {process.env.REACT_APP_MYVAR}
, or within the HTML with %REACT_APP_MYVAR%
.