I want to make checkbox group where one of checkboxes is aimed to control other. That special one will be used as "select all".
Here is my idea (which is partly working):
(defonce example-data (r/atom [{:id 1 :checked false} {:id 2 :checked false}]))
(defn check-all [e]
(swap! example-data #(setval [s/ALL :checked] (-> e .-target .-checked) %)))
(defn check-this [id]
(swap! example-data (fn [current]
(transform [s/ALL #(= (:id %) id) :checked] not current))))
(defn this-is-checked? [id]
(case id
:all (every? :checked @example-data)
(first (select [s/ALL #(= (:id %) id) :checked] @example-data))))
(defn example []
[:form
[:input (merge {:type "checkbox" :on-change #(check-all %)}
(if (this-is-checked? :all) {:checked "true"}))]
[:input (merge {:type "checkbox" :on-change #(check-this 1)}
(if (this-is-checked? 1) {:checked "true"}))]
[:input (merge {:type "checkbox" :on-change #(check-this 2)}
(if (this-is-checked? 2) {:checked "true"}))]])
And it works at the first sight - when you check first (the special one) it also check others, if you uncheck first it uncheck others, if you check all the other by hand, special one will be check too.
So, what is the problem then?
Reagent fires following warning when I first time check one of checkboxes.
react.inc.js:19500 Warning: ReagentInput is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://facebook.github.io/react/docs/forms.html#controlled-components
I've followed the link and found the story about Reacts controlled and uncontrolled components. I'm not a React connoisseur and it's not clear to me how could I make checkboxes checked only manipulating value
property of input
(if I understood the suggestion given here).
I definitely want to make checkboxes both available for manual change and controlled by state of example-data
.
Some clarification or an example from most experienced React/Reagent users are needed, I'm not experienced at all and all the comments are welcome.