--- tags: brew-js-react --- # Router ## Setup ### Step 1 &mdash; **Define routes** ```typescript import brew from "brew-js-react"; import router from "brew-js/extensions/router"; brew.with(router)(app => { app.useRouter({ routes: [ '/{view}/*', '/*' ] }); }); ``` Now the application will accept any path with the first segment set to a route parameter named `view`, e.g. for a path `/foo`, `app.route.view` will be equal to `foo`. :::success For more details on configuring router, visit [router section of the Brew.js Handbook](https://hackmd.io/@misonou/brew-js/%2F9Q3U33GOTvyPG7DXOU17Wg). ::: ### Step 2 &mdash; **Register view components** ```typescript import { registerView } from "brew-js-react"; export const Home = registerView( () => import("./views/Home"), { view: 'home' }); export const Foo = registerView( () => import("./views/foo"), { view: 'foo' }); ``` The second argument, which is matched against current route parameters (`app.route.*`), specifies when the view component are considered matched. ### Step 3 &mdash; **Render views** ```typescript import React from "react"; import ReactDOM from "react-dom"; import { renderView } from "brew-js-react"; import { Home, Foo } from "./views"; function App() { return renderView(Home, Foo); } const rootElement = document.getElementById('root'); render(<App />, rootElement); ``` When component is being rendered, `renderView` will try to match current route parameters against the registered views. The page `/home` will have the component exported from `./views/Home` rendered, as the path `/home` matches the route `/{view}/*`, which the route parameter `view` is equal to `home`. :::info If none is matched, the first view is selected and cause a redirection to the URL which represents the view. For example, both the page `/` and `/bar` will redirect to `/home`. ::: ## Example <iframe src="https://codesandbox.io/embed/brew-js-for-react-router-example-pkxg2?autoresize=1&fontsize=12&theme=light" style="width:100%; height:250px; border:0; border-radius: 4px; overflow:hidden;" title="Brew.js for React Router Example" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>