README
@scubadive/router
Router components for scubadive
Usage
import {
useBrowserHistory,
renderPage,
store,
routerReducer,
Link,
PageContext,
PageProvider,
PageConsumer,
} from "@scubadive/router";
Functions
useBrowserHistory()
Listens to events in the browser history.
renderPage(page, routes)
Return a component from the url of the desired page page
and the list of routes routes
.
store(routes)
store
is the return of the createStore
function.
Need a parameter routes
.
routerReducer(routes)
routerReducer
is also available to allow you to combine several reducers with combinedReducers
.
Need to feed the reducer with the routes
.
Components
Link
target
:
self
: display thehref
page instead of the current one.after
: displays thehref
page after the clicked one.root
(default value): displays thehref
page with all its parents.
const PageRed = () => {
return (
<RedBlock>
<Link href="/clients/10" target="root">
Next page (/clients/10)
</Link>
<Link href="/bills" target="after">
Next page (/bills)
</Link>
<Link href="/bills" target="self">
Next page (/bills)
</Link>
</RedBlock>
);
};
PageContext
PageProvider
wrapp all pages displayed one by one to allow each child to know where they are.
<PageProvider value={page} key={page}>
{React.cloneElement(route.action(), { match })}
</PageProvider>
PageConsumer
can be used to get the context from html content:
<PageConsumer>
{value => /* display something based on the context value */}
<PageConsumer/>
Or from javascript with the react hook:
const page = useContext(PageContext);
Full example
routes.js
import React from "react";
import { PageBlue, PageRed, PageBlack, PageGreen } from "./pages";
const routes = [
{
path: "/",
action: () => <PageBlue />,
},
{
path: "/clients",
action: () => <PageRed />,
parent: "/",
},
{
path: "/clients/:id",
action: () => <PageBlack />,
parent: "/clients",
},
{
path: "/bills",
action: () => <PageGreen />,
parent: "/clients/:id",
},
];
export default routes;
index.js
import { Provider } from "react-redux";
import routes from "routes";
import App from "./app";
import { store } from "@scubadive/router";
const rootEl = document.querySelector(".js-app");
ReactDOM.render(
<Provider store={store(routes)}>
<App />
</Provider>,
rootEl
);
app.js
import React from "react";
import { useSelector } from "react-redux";
import routes from "routes";
import { renderPage } from "@scubadive/router";
const App = () => {
useBrowserHistory();
const pages = useSelector((state) => state.pages);
return <>{pages.map((page) => renderPage(page, routes))}</>;
};
export default App;