Mobx React Router
This package provides a URL Router component based on Mobx and the History API.
The utilities and the component is this package are written in TypeScript and
they are meant to be used in a React TypeScript project.
Installation
npm install @blendsdk/mobx-router --save
yarn add @blendsdk/mobx-router
Usage
import {
createBrowserHistory,
initRouter,
IRoute,
Link,
Redirect,
ROUTE_404,
ROUTE_CATCH_ALL,
Router,
useRouter
} from "@blendsdk/mobx-router";
initRouter(createBrowserHistory());
const routes: IRoute[] = [
{
name: "dashboard",
path: "/",
component: Dashboard
},
{
name: "greet",
path: "/greet/:name/name",
component: Greet,
defaults: {
name: "Johny Bravo"
}
},
{
name: ROUTE_CATCH_ALL,
path: "",
component: Dashboard
}
];
const Main = () => {
return <Router routes={routes}></Router>;
};
ReactDOM.render(<Main />, document.getElementById("root"));
404 Route
If you do not wish to configure a catch all route then you have the option to configure a 404
route to catch the unmatched location changes. The Router component provides a default 404 route
if the incoming URL is not matched and there is also no catch all route.
To customize the built-in 404 route, just configure a route similar to:
....
{
name: ROUTE_404,
path:"/not-found",
component: My404PageComponent
}
....
The Link component
This component provides an easy way to render a link that is handled by the Router.
Properties:
to is the name of the route
params is a key/value pare to set the route parameters
reload an optional boolean that if set to true will reload the page when the link is clicked
<Link to='name-of-the-route' params={{ name: "sally" }} reload={true}>
Text goes here...
</Link>
<Link to='order-items' params={{ order: someValue }}>
Text goes here
</Link>
The Redirect component
This component is similar to the Link component except that is does not generate a user interface.
When this component is rendered it will immediately redirect the to provided route.
Properties:
to is the name of the route
params is a key/value pare to set the route parameters
reload an optional boolean that if set to true will redirect by reloading the page.
const SomeComponent = () => {
return authenticated ? <Dashboard /> : <Redirect to='login' params={{ param1: true }} reload={true} />;
};
Hooks
In order to get a reference to the router you can make use of the useRouter hook
const Component = () => {
const router = useRouter();
...
};
API
The router component provides the following API
The go method
const router = useRouter();
router.go('name-of-the-route', { param1,'value1' });
router.go('name-of-the-route', { param1,'value1' }, true);
The generateUrl
This method generates a URL based on a path name or a parameters.
const router = useRouter();
const url = router.generateUrl("order-item", { orderNumber: 1000 });
License
MIT