Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
(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)]
[:input {:type :checkbox
:on-change #(swap! state choose-fruit choice checked?)
:checked checked?}]
[:span choice]]))
(defn fruit-list [chosen-fruit]
(for [choice choices]
^{:key choice}
[fruit-checkbox chosen-fruit choice])])
(defn content []
[: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"))
<meta charset="UTF-8">
<title>Fruit checkboxes</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<div id="content"></div>
<script src="main.js"></script>
html {
font-size: 16px;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.