Skip to content Skip to sidebar Skip to footer

How To Pass A Prop To Every Component In React.js?

I'm setting up a site using react.js. the client receives a massive json through ajax that is then used to populate all the necessary fields, graphs, etc. Seeing as this json will

Solution 1:

As React's documentation states, you could have components communicate by integrate a global event system, and then subscribe to an application-data event from all your components, in componentDidMount(). This way, each time you will emit the application-data event from within the code responsible for pulling the website data, all components will receive that data. At that point, you can call setState().

Please be careful and unbind the events once a component goes "out of scope", inside componentWillUnmount().

Failing to do so will result in memory leaks, as you will have the event handler dangling, and it will be called each time you pull the website data, even if your Component's instance has been removed from the DOM.

You could also try to make your components pull data by themselves, as sending a huge JSON around, is not the best solution. I mean, each component should use the data it needs, in order to work, not the whole website data. The way I would alter this would be by parsing the JSON object and storing it for reference in a variable, on a scope that is accessible to all components, and use the event system to only notify the components that the data is ready, and each component would go to the global data object and get their data.

Example(pseudo-code):

XHR.getData
XHR.onReadyState => GlobalNameSpace.data = data
EventSystem.PUBLISH('application-data')

// component code
Component {
    EventSystem.SUBSCRIBE('application-data') => 
        dataNeededForInit  = GlobalNameSpace.data.componentXData
}

Reference: https://facebook.github.io/react/tips/communicate-between-components.html

Solution 2:

Context might fit the bill. It might not be particularly tidy solution but perhaps that would be a starting point for you.

Post a Comment for "How To Pass A Prop To Every Component In React.js?"