Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access window variables in React

I am working on a React Redux app. The base template for my React app is something like

 <div id="react"></div>
 <script type="text/javascript" src="/static/bundles/main-hash.js" ></script>
 <script>
   window.userData = {a: 1, b:2}
 </script>

I want to use the variable userData in my react app. window.userData returns undefined at almost all places (reducers, componentDidMount of a component etc.). But if I log the window object, I can see in my console that there is a userData variable in it.

To sum it up console.log(window, window.userData) returns -

Window undefined where Window in which window is a collapsed tree. Uncollapsing it, the userData variable can be seen in it.

like image 658
Osho Dhiraj Avatar asked Apr 12 '26 19:04

Osho Dhiraj


1 Answers

Please move your script tag before your react component script tag. It should work.

I mean you should create userData member in windows object before you use it.

like image 128
Karpak Avatar answered Apr 15 '26 09:04

Karpak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!