A simple React router
usage:
var React = require('react/addons');
var wrt = require('wrt');
var Router = wrt.Router;
var Route = wrt.Route;
React.render(
<Router root="/">
<Route path="/" handler={function() { return <h1>Root</h1>; }} />
<Route path="/sub" handler={function() { return <h2>Sub</h2>; }} />
</Router>,
document.body
);
This project is nowhere near ready and this readme is just a spot for me to flesh out ideas and features. Check out the demos
Basic API
When you do var wrt = require('wrt')
it comes with two react classes, Router and Route (wrt.Router, wrt.Route
)
The basic (and default) case is
/
but you can pass something like/root/
so that when you are on/root/sub
you get routed to/sub
ex:<Router root="/admin"></Router>
===
The location object to use for routing. Defaults to
window.location
(duh). If you choose to pass something other thanwindow.location
it must be an object with ahref
property
This is used to identify the route in the router's
routes
hash, it's also used as the link url if nopath
is provided, it's also passed as a prop to all the other routes so you can use it as shown in the nextRoute
prop...
This can be a function or a react class. If it's a function it gets injected a props object as it's first param. If it's a react class it get's it props populated with the same object which has the following values:
This is a hash of all the routes so you can do something like this:
<Route handler={function(props) { return <a href={props.routes.editUser.href}>Edit</a>; }} />Or
var Linker = React.createClass({ render: function() { return <a href={this.props.editUser.href}>Edit</a> } }); <Router ... /> <Route handler={Linker} /> </Router>
This let's you change the location also, the reason you would use this way over the
props.routes
is because the location object may not bewindow.location
so changing the url won't have any effect.
The Router
class also has a static method createClass
which let's you partially apply a base router that you can extend. Here's an example:
var MainRouter = Router.createClass(
<Router>
<Route name="root" path="/" handler={rootView} />
<Route name="edit" path="edit" handler={editView} />
</Router>
);
var sharedLocation = {href="/"};
var SidebarRouter = (
<MainRouter location={sharedLocation} />
);
var FooterRouter = (
<MainRouter location={sharedLocation} />
);
var RightbarRouter = (
<MainRouter location={{href="/"}}>
<Route name="another" handler={anotherView} />
</MainRouter>
);
Do you need it? Probably not. Why did I make it? Because it was fun and it's 3 lines of code
More to come!!
See test/router for more info