Basic Routing and Rendering
Routes are defined using route builders. Among those provided by Rocon, the most commonly used one is the Path route builder.
Using Path Route Builder
The next example defines two routes, namely /foo
and /bar
, using Rocon.Path
. It first initializes a new Path route builder by calling Rocon.Path()
, and then calls the route
method to add routes to it one by one.
import Rocon from "rocon/react";
// Alternatively you can choose Rocon by name
// import { Rocon } from "rocon/react";
// You can also import functions directly from rocon/react
// import { Path } from "rocon/react";
const toplevelRoutes = Rocon.Path()
.route("foo", (route) => route.action(() => <p>This is foo</p>))
.route("bar", (route) => route.action(() => <p>This is bar</p>));
The route
method receives a callback function with one parameter route
. It has an action
method that receives a function that returns a React node. By calling the action
method, you can register what is rendered when that route (/foo
or /bar
) is visited.
Using RoconRoot
Rocon requires your app to be wrapped by a component named RoconRoot
. It maintains a history
object and tracks history change. A common set up of RoconRoot
will look like:
import { RoconRoot } from "rocon/react";
const App: React.FC = () => {
return (
<RoconRoot>
<Routes />
</RoconRoot>
);
};
By default, RoconRoot
automatically creates a History instance by calling createBrowserHistory. To provide your own History instance, pass it via the history
prop.
const App: React.FC = () => {
const history = useMemo(() => {
return createMemoryHistory();
}, []);
return (
<RoconRoot history={history}>
<Routes />
</RoconRoot>
);
};
Using useRoutes() to Render Resolved Route
Now you have a route builder defined and RoconRoot
set up. What you do next is to render the contents using the useRoutes
hook provided by Rocon.
The useRoutes
hook receives a route builder and returns a React node. A typical component that uses useRoutes
will look like:
import { useRoutes } from "rocon/react";
const Routes: React.FC = () => {
return useRoutes(toplevelRoutes);
};
Now, you should see This is foo
rendered if you visit /foo
. If you visit /bar
, This is bar
should be rendered.