Skip to content

Instantly share code, notes, and snippets.

@prestancedesign
Forked from saskali/reagent-color-sorting
Last active December 8, 2020 14:02
Show Gist options
  • Save prestancedesign/4b44a188ea3977b75603d312900656fb to your computer and use it in GitHub Desktop.
Save prestancedesign/4b44a188ea3977b75603d312900656fb to your computer and use it in GitHub Desktop.
Re-frame color example
(ns color-sorting.core
(:require [reagent.core :as reagent]
[reagent.dom :as dom]))
(def colors ["blue" "yellow" "green" "purple" "red"])
(def color-row (reagent/atom ["blue" "yellow" "green"]))
(def sorted-color-row (reagent.ratom/reaction (sort @color-row)))
(defn square [color]
[:svg {:style {:background color
:width "20px"
:height "20px"}}
[:rect]])
(defn sorted-colors []
;; random generation for sequence of color cubes.
;; using reagent's reaction for the sorted sequence allows
;; repeated usage of `sorted-color-row` while only being calculated once
[:div
[:button {:on-click #(swap! color-row conj (->> colors count rand-int (get colors)))} "new color!"]
[:button {:on-click #(reset! color-row [])} "reset"]
[:p "original:\n" (map square @color-row)]
[:p "sorted:\n" (map square @sorted-color-row)]
[:p "reverse:\n" (reverse (map square @sorted-color-row))]])
(dom/render [sorted-colors] (.getElementById js/document "app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment