What is the standard way of setting React Component states based on routes? I have the following React/Backbone example:
var myApp = React.createClass({
render: function() {
return (
<div className={this.state}></div>
);
}
})
var App = Backbone.Router.extend({
routes: {
"": "home",
"create": "create"
}
});
var app = new App();
app.on('route', function(page) {
// How do I set state on myApp??
})
React.renderComponent(<myApp />, document.body);
Backbone.history.start();
I believe I need to be able to set the state of myApp
from outside, but how? I can’t find any examples on this.
Or maybe I’m thinking in the wrong direction here, is there a better way of organizing routes together with React?
i have no idea what the general solution is, but what I, a bit simplified, did is
var App = Backbone.Router.extend({
routes: {
"": "home",
"create": "create"
}
});
var myComponent = false
function loadOrUpdateComponent(urlState) {
if (!myComponent) {
myComponent = <MyApp urlState={urlState}/>
React.renderComponent(myComponent, document.body);
} else {
myComponent.setProps({urlState:urlState})
}
}
var app = new App();
app.on('route', function(page) {
loadOrUpdateComponent(page)
})
Backbone.history.start();
So the actual answer to your question is to use .setProps(newProps)
on a previously rendered component. i load the component in the event handler because else you get a race condition between renderComponent and setProps wich might lead to bad things.
Edit:
Ive since updated my route handling, i now simply do
router.on('list', function() {
React.renderComponent(<Component data={someData} />, mountPoint)
})
router.on("details", function(id) {
React.renderComponent(<Component data={someData} selected={id} />, mountPoint)
})
router.on("extra-details", function(id) {
React.renderComponent(
<Component data={someData} selected={id}>
<SpecificExtraComponent />
</Component>
, mountPoint
)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With