I have two components; menu and info. I need to share the data between the two components. I'm using Facebook Flux pattern. The store class has a change detection by EventEmitter. The detection works between parent and children relationship.
The blue is menu. The red is info component. My website didn't use ReactJS before. I am trying to use ReactJS into part of the site. I guess that using ReactJS for whole app is one possible solution, react-route..?, but I cannot do that in this time.
Does anyone know about that?
================================
Edit 1
I posted my whole code to this gist.
https://gist.github.com/y-zono/e1abf9e85a4707d81286b49f6a7f0117
My goal is menu and info counters show same value. Now only menu counter is increased.
================================================
Edit2 Solved
var React = require('react');
var ReactDOM = require('react-dom');
var Menu = require('./components/Menu.react');
var Info = require('./components/Info.react');
var CommonStore = require('./stores/CommonStore');
function renderMenu() {
var state = CommonStore.getState();
ReactDOM.render(
<Menu data={state} />,
document.getElementById('menu')
);
}
CommonStore.addChangeListener(renderMenu);
renderMenu();
function renderInfo() {
var state = CommonStore.getState();
ReactDOM.render(
<Info data={state} />,
document.getElementById('info')
);
}
CommonStore.addChangeListener(renderInfo);
renderInfo();
Instead of subscribing to the stores at your component level, why not subscribe where you render the components (e.g. menu.js)?
You could wrap your rendering code in a function, and in that function read the store's state before passing it as a prop to your component. You would call render()
manually to do your first render, but also subscribe to the store passing the render function as a callback:
// menu.js
var React = require('react');
var ReactDOM = require('react-dom');
var Menu = require('./components/Menu.react');
var CommonStore = require('../stores/CommonStore');
function render() {
var state = CommonStore.getState();
ReactDOM.render(
<Menu data={state} />,
document.getElementById('menu')
);
}
CommonStore.addChangeListener(render);
render();
Note: I'm not sure what getters your store has, so i've just written some example code.
Your component code would then simply be:
// ./components/Menu.react.js
var React = require('react');
var CommonActionCreators = require('../actions/CommonActionCreators');
var Menu = React.createClass({
_handleClickMenu: function() {
CommonActionCreators.setMenuClieckOn();
}
});
And then repeat the process for the Info
component.
This fiddle shows an example of this approach working in practice (with some dummy components, store and action creators), to prove that the concept works: https://jsfiddle.net/vgskht45/1/