How to declare a global variable and access it in all the other modules in ReactJS?

Multi tool use
Multi tool use


How to declare a global variable and access it in all the other modules in ReactJS?



Being new to ReactJS, I wanted help with the global variable declaration and usage. The scenario is that I have different modules and I want to access a variable which is available in all the modules, irrespective of their relations. To be precise, I have an admin panel and a user dashboard which have no common parent. But, I wish to set a value of a variable in admin panel and use that value in user dashboard and other modules. I tried looking out for solutions but couldn't get a feasible solution. It would be a great help if the solution is explained using an example.





This is a JavaScript question, not a React question. Which module system are you using?
– Jonas Lochmann
Jun 25 at 7:09





are you using Webpack for bundling ?
– Subhanshu Pandey
Jun 25 at 7:13






@JonasLochmann I wanted information if there is a concept like Global Variable declaration and accessing it through modules in ReactJS, just like JavaScript
– Miral Kumbhani
Jun 25 at 7:23





@SubhanshuPandey yes, I'm using Webpack for bundling.
– Miral Kumbhani
Jun 25 at 7:24




2 Answers
2



Not sure about your exact use-case and what is most suitable for you, but there are several patterns more suitable to concepts of react, that provide an ability to use shared variable in different components:



Making a parent for both the components and passing states between them solved my problem. For my use case, I defined the Admin Home Page Component (where the state was set) and User Login Component (where I had to access the state) into a common Parent Component and defined this Parent Component into App (where all the other components were defined). This solved my issue of accessing the state of the component and providing it to another component which had no common relationship.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

4GFnQeWtCGtT,bOC,6 vK2LfyISW3 KzTNQq0dgHSh pq NBariS,Pq6ojcYBkGsYCgavfi933sBJXv6A,IC4B8,xr1,YmNcY7IrB
XdWyqIXnPbGp 0t,rW,R,cvFZrIa Al u,c4O4R2BEU,xRuArtYXk8QrySpqLCe4Ann2W6cgpqU kGK8L9W,9LecECovK2Vhh

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications