In my project I deiced to include React Router. One of my Reflux Stores need to figure out the path based on some BL and than change it. First I've tried including the Navigation mixin inside the Store and running this.transitionTo("Foo"); which threw an error : "Uncaught TypeError: Cannot read property 'router' of undefined".
Someone suggested that : "this.transitionTo is probably accessing the router property through contexts (this.context.router) which do not exist in RefluxJS stores" ... Which I understand.
However there must be a way to change the router path from a Store Programmatically, or any given external JS Module.
My Code goes something like this:
// routes.js
//////////////////////////////////////////////////////////
var Router = require('react-router');
var Route = Router.Route;
var App = require('./app');
var Comp = require('./components/comp');
var routes = (
<Route path='/' handler={App}>
<Route name='Foo' path='/foo' handler={Comp}/>
</Route>
);
module.exports = routes;
// main.js
//////////////////////////////////////////////////////////
var React = require('react');
var Router = require('react-router');
var routes = require('./Routes');
var appElement = document.getElementsByTagName('body');
Router.run(routes, Router.HistoryLocation, function(Root, state) {
React.render(<Root params={state.params} query={state.query} />, appElement);
});
// comp.js
//////////////////////////////////////////////////////////
var React = require("react");
var Reflux = require("reflux");
var Actions = require("../actions/actions.js");
var SomeStore = require("../stores/some-store.js");
var Comp = React.createClass({
render: function() {
return (
<h1>Hello World</h1>
);
}
});
module.exports = Comp;
// store.js
//////////////////////////////////////////////////////////
var SomeStore = Reflux.createStore({
onSomeAction: function() {
// CHANGE ROUTER PATH HERE TO /foo
}
});
module.exports = SomeStore;
Any help will be appreciated!
The router is only known by the components (React views). You need to pass the router from the context as a parameter in your action. That way, you can use this parameter to make a transition to a different route. I've been using it this way.
I have something like below in one of my action listeners in a store.
_onMyAction: function (router) {
MyApi.doSomething()
.then(function (id) {
// do something ...
router.transitionTo('myNewRoute', { ref: id });
})
.catch(function(message) {
// handle message
});
}
Reflux actions return a promise, so rather than doing this in the store (which IMO is wrong) you can do it in your component:
Actions.someAction().then(function() {
// route transition
});
Whether this is completely right... well, I'm not sure the community has really settled on an opinion.
Related
I'm attempting to run the following code:
"use strict";
var React = require('react');
var Router = require('react-router');
var Link = Router.Link;
var Material = require('material-ui');
var ThemeManager = new Material.Styles.ThemeManager();
var Colors = Material.Styles.Colors;
var dropdown = Material.Icons.NavigationArrowDropDown; //This icon cannot be found
var Home = React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object
},
getChildContext: function () {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
},
componentWillMount: function () {
ThemeManager.setPalette({
accent1Color: Colors.cyan500
});
},
render: function () {
return (
<div>
<Material.AppBar title="Test" showMenuIconButton={false}>
</Material.AppBar>
<Material.List>
<Material.ListItem primaryText={"Queue"} leftIcon={<Material.Icons.NavigationChevronLeft/>} />
<Material.ListItem primaryText={"Log"} leftIcon={<Material.Icons.NavigationArrowDropDown/>} />
<Material.ListItem primaryText={"Settings"} />
</Material.List>
<Material.Paper>
<span>This is some text</span>
<Material.RaisedButton label="Super Secret Password" primary={true}/>
</Material.Paper>
</div>
);
}
});
module.exports = Home;
I've included the necessary packages and the code runs fine if I don't include
Material.Icons.NavigationArrowDropDown;
I've navigated to material-ui (0.11.1) and the file does exist there as an export in the following path:
lib > svg-icons > Navigation > Arrow_drop_down.js and the source code is as follows:
'use strict';
var React = require('react/addons');
var PureRenderMixin = React.addons.PureRenderMixin;
var SvgIcon = require('../../svg-icon');
var NavigationArrowDropDown = React.createClass({
displayName: 'NavigationArrowDropDown',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M7 10l5 5 5-5z' })
);
}
});
module.exports = NavigationArrowDropDown;
However, when compiling and running the application it cannot find the item and complains it does not exist, yet the other item
Material.Icons.NavigationChevronLeft
Gets found without issue. This file (with the exclusion of my router and app.js) are my entire project.
Since both files exist in the same folder, I cannot understand why the one reference is found and the other isn't?
The error occurs at runtime and jsLint doesnt pick it up. Additionally, when removing the listItem icon my page renders correctly. The problem appears to be tied directly to this component.
Additional Note: I have removed the var dropdown, it was there merely to demonstrate how the export is not being found from Material UI.
tl;dr : Material UI Icon class in the same folder as another Icon class is not being picked up. Why?
As you can see in src/index.js, NavigationArrowDropDown isn't being set on Material.Icons, while NavigationChevronLeft is. The component is used in other places, but is never publicly exposed through material-ui's main export.
However, you can still require it like you would any other file:
var NavigationArrowDropDown = require('material-ui/lib/svg-icons/navigation/arrow-drop-down');
Looking at the README, it looks like this is the recommended way to reach single components.
I am writing a authentication module in Flux, actions : auth,auth_success,auth_error. I am thinking when action auth_error occur, the router will go to '/login'. When action, action, auth_success occur, the router will go to '/dashboard'.
But it seems to be wrong because action only goes to dispatcher. I don't know how to do route the callbacks. Maybe check the store value?
You have to mixin your React class with Route.Navigation object, for instace
/** #jsx React.DOM */
var React = require('react');
var Router = require('react-router')
, Navigation = Router.Navigation;
var UserStore = require('user-store');
var YourClass = module.exports = React.createClass({
mixins:[Navigation], //This is very important
getInitialState: function() {
return {};
},
componentWillMount: function(){
UserStore.addChangeListener(this._method);
},
componentWillUnmount: function(){
UserStore.removeChangeListener(this._method);
},
render: function() {
return (
<div>
</div>
);
},
_method: function() {
// From here you can call methods of Navigator Object
this.transitionTo('SomeRouteName'); //This method will render the specified <Route>
}
});
For further information you can check
https://github.com/rackt/react-router/blob/master/docs/api/mixins/Navigation.md
In order to change the route and according to flux architecture, you should call transitionTo from a callback of some User Store you should have.
I added an example to the code, you may customise it to your specific case.
Happy coding!
I am building a application using Facebook flux architecture of React JS. I have build the basic part of app where I have a login form. I am fetching the the result from node server to validate user at the store, I am getting the result from server, Now I got stuck that how can I redirect the user to home page after success.
I have read about the react router component and I am able to redirect at the client side but not able to redirect at the time of fetching result from ajax in Store. Please help me.
You need to use the transitionTo function from the Navigation mixin: http://git.io/NmYH. It would be something like this:
// I don't know implementation details of the store,
// but let's assume it has `login` function that fetches
// user id from backend and then calls a callback with
// this received id
var Store = require('my_store');
var Router = require('react-router');
var MyComponent = React.createClass({
mixins: [Router.Navigation],
onClick: function() {
var self = this;
Store.login(function(userId){
self.transitionTo('dashboard', {id: userId});
});
},
render: function() {
return: <button onClick={this.onClick}>Get user id</button>;
}
});
It worked for me when I added to the react element properties a require for the router and used the router like this:
// this is the redirect
this.context.router.push('/search');
// this should appear outside the element
LoginPage.contextTypes = {
router: React.PropTypes.object.isRequired
};
module.exports = LoginPage;
This should work
var Store = require('Store');
var Navigatable = require('react-router-component').NavigatableMixin
var LoginComponent = React.createClass({
mixins: [ Navigatable ],
onClick: function() {
Store.login(function(userId){
this.navigate('/user/' + userId)
}.bind(this));
},
render: function() {
return <button onClick={this.onClick}>Login</button>;
}
});
Just want to get some basic routing up and going. Having seen a number of examples I thought the code below should work, but when I run I get the error "Unable to get property 'doChat' of undefined or null reference". Do I have the initialization sequence wrong?
require(["marionette", "jquery.bootstrap", "jqueryui"], function (Marionette) {
window.App = new Marionette.Application();
App.start();
App.addRegions({
//add some regions here
});
//Set up routing
var AppRouter = Marionette.AppRouter.extend({
appRoutes: {
"": "doDefault",
"chat": "doChat"
},
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
});
var router = new AppRouter();
//History
if (Backbone.history) {
Backbone.history.start();
}
})
The AppRouter allows two types of routes, standard backbone routes as defined in the routes property and routes which call functions in another object defined in the appRoutes property.
So to get you above code working, you can do one of two things. The quickest is simply to change the appRoutes property to routes which will do normal backbone routing. The second option is to create another object and pass that to the AppRouter as the controller during instantiation:
var myController = {
doDefault: function () {
alert("doing default...")
},
doChat: function () {
alert("doing chat...")
}
}
var router = new AppRouter({
controller: myController
});
This is detailed in the AppRouter documentation.
Let's say I have one root Ractive on the page,and various widgest to show when an hypothetic backbone router navigate to a route :
var widget1=Ractive.extend({template:"<div>{{foo}}</div>"});
var widget2=Ractive.extend({template:"<div>{{bar}}</div>"});
var view=new Ractive({
template:"<nav></nav><widget />",
components:{widget:widget1}
});
var Router=Backbone.Router.extend({/* the code ... */})
so widget1 would be shown when I navigate to /widget1 and widget2 when the route is /widget2,
What would be the best way to swap widgets depending on the current route without creating seperate root Ractives or hiding/showing widgets? thanks.
An alternative solution to my previous suggestion, which allows routes to be set in a more dynamic fashion (i.e. without having to declare them in a template up-front):
<nav>...</nav>
<!-- we have a single <route> component representing all possible routes -->
<route current='{{currentRoute}}'/>
This could be implemented like so:
Ractive.components.route = Ractive.extend({
template: '<div class="container"></div>',
init: function () {
this.container = this.find( '.container' );
this.observe( 'current', function ( currentRoute ) {
var View = routes[ currentRoute ];
if ( this.view ) {
this.view.teardown();
}
this.view = new View({
el: this.container
});
});
}
});
Then, to switch routes:
router.on( 'route', function ( route ) {
ractive.set( 'currentRoute', route );
});
With this approach all you'd need to do is register all the possible routes at some point in your app:
routes.widget1 = Ractive.extend({template:"<div>{{foo}}</div>"});
...and so on. If necessary you could interact with each view object by retrieving a reference:
route = ractive.findComponent( 'route' );
route.view.on( 'someEvent', someEventHandler );
One way would be to explicitly include the components representing each route in the top-level template:
<nav>...</nav>
{{# route === 'widget1' }}
<widget1/>
{{/ route === 'widget1' }}
{{# route === 'widget2' }}
<widget2/>
{{/ route === 'widget2' }}
Then, you could do something like:
router.on( 'route', function ( route ) {
ractive.set( 'route', route );
});
This would tear down the existing route component and create the new one.
If your route components had asynchronous transitions, you could ensure that the new route didn't replace the old route until any transitions had completed by doing this:
router.on( 'route', function ( route ) {
ractive.set( 'route', null, function () {
ractive.set( 'route', route );
});
});
(Note that as of version 0.4.0, ractive.set() will return a promise that fulfils when any transitions are complete - though callbacks will still be supported.)
Having said all that I'd be interested to hear about any other patterns that people have had success with.