0

I have problem with sharing objects that were created within some component. I am curious how can i access those objects in another component. Can i create a global variable that is accessible within all classes? Unfortunately, i cannot find any relative answers or project in the web.

chris
  • 58
  • 1
  • 8

2 Answers2

2

Create a closure within the component that will hold all the data you want to make available to other components, then export it alongside your component. whenever you want to use that shared data, require the closure the same way you require a component.

ps: probably it's better to use any variant of Flux, I recommend Redux

taha
  • 997
  • 9
  • 17
  • Could you give me an example how can i implement communication between components, or at least how to create global variable in Redux. I cannot find any example projects / problem concerning such problem – chris Jul 13 '17 at 12:18
  • @chris: I almost regret mentioning *closures*. if you want to do it the right way, go for *Redux*, it's easy to use and extremely elegant. – taha Jul 13 '17 at 15:45
  • I found this Question : https://stackoverflow.com/questions/21285923/reactjs-two-components-communicating it might be interesting – taha Jul 13 '17 at 15:46
1

Well if you wanna give a children some of the parent object you can do in the parent:

<Children anything={yourObject} />

and access to yourObject in the children using:

const childrenObject = this.props.anything

But this will work in a simple react app, If you are planning to do something more complicated then you should try to learn redux, it will give your app a global state called Store where you will put whatever you want and access anywhere in your app

https://www.codementor.io/mz026/getting-started-with-react-redux-an-intro-8r6kurcxf

kikiwie
  • 390
  • 1
  • 3
  • 12