Backbone.router and React states

What is the standard way to set route-based React Component states? 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 that I need to set myApp state externally, but how? I can not find examples on this.

Or maybe I'm thinking of the wrong direction here, is there a better way to organize routes with React?

+8
javascript url-routing reactjs
source share
1 answer

I have no idea what a general solution is, but I simplified it a bit

 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) for a previously processed component. I load the component into the event handler because otherwise you will get a race condition between renderComponent and setProps, which can lead to bad things.

Edit:

Ive since updated my route processing, now I just 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 ) }) 
+12
source share

All Articles