Routes
The routes in the routes configuration represent the user interface of your application. As most user interfaces are hierarchical in nature, so can the routes be nested to represent shared pieces of user interface.
import Routes from 'react-sprout';
import App from './app.jsx';
import Home from './home.jsx';
import Admin from './admin.jsx';
import Users from './users.jsx';
import Posts from './posts.jsx';
let Router = Routes(
<App path="app">
<Home path="home" />
<Admin path="admin">
<Users path="users" />
<Posts path="posts" />
</Admin>
</App>,
);
The Router
element will progressively match segments from the current url to the nested path properties of the routes to figure out what to render.
The url /app/admin/posts
for example has three segments; app
, admin
and posts
which will respectively match the paths of the App
, Admin
, and Posts
routes.
These matched routes form the element structure for the page at this url.
<App>
<Admin>
<Posts />
</Admin>
</App>
A route component can render its child route like any other react component would, by using props.children
:
function Admin(props) {
return (
<main>
<h1>Admin</h1>
<section>{props.children}</section>
</main>
);
}
Note that there is no page at /app/admin
, as the url matching keeps going until there are no chid routes left to match.
If you also wanted a page at /app/admin
, the routes configuration would look like this
let Router = Routes(
<App path="app">
<Home path="home" />
<Admin path="admin" />
<AdminLayout path="admin">
<Users path="users" />
<Posts path="posts" />
</AdminLayout>
</App>,
);
While each route in the previous example specified exactly one segment of the url, this is not a requirement. A route does not need to add anything to the url, or it can specify multiple url segments at once.
let Router = Routes(
<App path="app">
<Home />
<Admin path="admin">
<Users path="users" />
<Posts path="content/posts" />
</Admin>
</App>,
);
- The
Home
route does not have a path property and will not add anything to the url, so will be rendered at/app
. - The
Posts
route adds 2 url segments at once to the url, it will be rendered at/app/admin/content/posts
.
If the Admin
route does not render anything but props.children
, it is not necessary to group the Users
and Posts
routes.
This is also a viable route configuration:
let Router = Routes(
<App>
<Home />
<Users path="admin/users" />
<Posts path="admin/content/posts" />
</App>,
)
You should however always group multiple routes if there is a shared piece of user interface. And let the parent take care of rendering that shared part of the user interface.