Skip to content

Instantly share code, notes, and snippets.

@lambdahands
Last active May 3, 2017 15:38
Show Gist options
  • Save lambdahands/121dea0c283fb8dddd26ec25db7da7af to your computer and use it in GitHub Desktop.
Save lambdahands/121dea0c283fb8dddd26ec25db7da7af to your computer and use it in GitHub Desktop.
(ns nightcoders.fruit-checkboxes
(:require [reagent.core :as r]))
;; Initial State
(def choices [:apple :apricot :banana :mango :orange :plum])
(def max-choices 2)
(def state (r/atom []))
;; State transforms
(defn bounded [max-size coll]
(drop (- (count coll) max-size) coll))
(defn bounded-conj [coll v max-size]
(bounded max-size (conj coll v)))
(defn choose-fruit [chosen choice checked?]
(if checked?
(remove #(= choice %) chosen)
(bounded-conj (vec chosen) choice max-choices)))
;; Views
(defn fruit-checkbox [chosen-fruit choice]
(let [checked? (contains? (set chosen-fruit) choice)]
[:div
[:input {:type :checkbox
:on-change #(swap! state choose-fruit choice checked?)
:checked checked?}]
[:span choice]]))
(defn fruit-list [chosen-fruit]
[:div
(for [choice choices]
^{:key choice}
[fruit-checkbox chosen-fruit choice])])
(defn content []
[:div
[:h2 "Which fruits do you want? Pick two or fewer."]
(let [chosen-fruit @state]
[fruit-list chosen-fruit])])
(r/render-component [content] (.querySelector js/document "#content"))
<html>
<head>
<meta charset="UTF-8">
<title>Fruit checkboxes</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="content"></div>
<script src="main.js"></script>
</body>
</html>
html {
font-size: 16px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment