Last active
May 3, 2017 15:38
-
-
Save lambdahands/121dea0c283fb8dddd26ec25db7da7af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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")) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
html { | |
font-size: 16px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment