HyperRouter is a DSL wrapper for ReactRouter v4.x to provide client-side routing for Single Page Applications (SPA). As the user changes "pages" instead of reloading from the server your App will mount different components.
Routes are defined with special pseudo components you call inside the router/components. The router determines which of the routes to actually mount based on the current URL.
The block will be given the match, location, and history data:
classMyRouter... render(DIV) doRoute('/:name') do|match, location, history|H1 { "Hello #{match.params[:name]} from #{location.pathname}, click me to go back!" }.on(:click) { history.go_back }endendend
The Hyperstack::Router::Helpers is useful for components mounted by the router.
This automatically sets the match, location, and history params,
and also gives you instance methods with those names.
You can use either params.match or just match.
and gives you access to the Route method and more.
This allows you to create inner routes as you need them.
classMyRouterincludeHyperstack::ComponentincludeHyperstack::Router::HelpersincludeHyperstack::Router render(DIV) doRoute('/:name', mounts: Greet)endendclassGreetincludeHyperstack::ComponentincludeHyperstack::Router::Helpers render(DIV) doH1 { "Hello #{match.params[:foo]}!" }Route(match.url, exact: true) doH2 { 'What would you like to do?' }endRoute("#{match.url}/:activity", mounts: Activity)endendclassActivityincludeHyperstack::ComponentincludeHyperstack::Router::HelpersincludeHyperstack::Router render(DIV) doH2 { params.match.params[:activity] }endend
Normally routes will always render alongside sibling routes that match as well.
Going to /goodbye would match /:name as well and render Greet with the name param with the value 'goodbye'. To avoid this behavior and only render one matching route at a time, use a Switch component.
Pre-rendering is automatically taken care for you under the hood.
Setup
To setup HyperRouter:
Install the gem
Your page should render your router as its top-level-component (first component to be rendered on the page) - in the example below this would be AppRouter
You will need to configure your server to route all unknown routes to the client-side router (Rails example below)
With Rails
Assuming your router is called AppRouter, add the following to your routes.rb
root 'Hyperstack#AppRouter'# see note belowmatch '*all', to: 'Hyperstack#AppRouter', via: [:get] # this should be the last line of routes.rb
Note:
root 'Hyperstack#AppRouter' is shorthand which will automagically create a Controller, View and launch AppRouter as the top-level Component. If you are rendering your Component via your own COntroller or View then ignore this line.