clojure-demos/resources/public/documents/reitit-demo.org

1.5 KiB

Routing

Routing with reitit is all about data, you store your routes as nested vectors of hash maps. the hash map should take a name and view param at least but you can add in params and validate the data.

Reitit works as a backend and frontend routing library so you can share routes between the two.

These are a few simple routes, the last takes parameters and does validation checking against the values.

(def routes
  [["/"
    {:name ::frontpage
     :view 'home-page-function}]

   ["/about"
    {:name ::about
     :view 'about-page-function}]

   ["/item/:id"
    {:name ::item
     :view 'item-page-function
     :parameters {:path {:id int?}
                  :query {:foo keyword?}}}]])

You need to connect your routes data structure to ref/start! this function take's your own function where you can handle what should happen on route change, in this example an atom is updated causing react to render the new page.

(def site-state (reagent/atom nil))

  (rfe/start!
   (rf/router routes {:data {:coercion rss/coercion}})
   (fn [m] (swap! site-state assoc :current-route m))
   ;; set to false to enable HistoryAPI
   {:use-fragment true})

To create a link to a route, you can use the rfe/href function which takes a lookup key which you specified in your routes, in this instance the key is name spaced to the current namespace.

[:a {:href (rfe/href ::frontpage)} "example link"]