Welcome! Please see the About page for a little more info on how this works.

0 votes
in ClojureScript by
closed by
(defn- menu-item
  [value-fn label-fn state lang index item]
(let [value (value-fn item)
    label (label-fn item lang)]
^{:key index}
[:> m/MenuItem {:value   value
                :data-cy (-> (str value) (str/lower-case) (str/replace " " "-") (str "-menu-item"))}
 [:> m/Checkbox {:checked (= (value-fn state) value)}]
 [:> m/Typography {} label]
(defn select
  [{:keys [data state-fn disabled? label value-fn label-fn data-cy variant]}]
  (let [rf-lang   (rf/subscribe [:current-language])
        label-fn1 (or label-fn (fn [item lang] (value-fn item)))]
    (fn [{:keys [data state-fn disabled? label value-fn data-cy variant]}]
      (let [lang  @rf-lang
            state (state-fn)
            props (cond->
                    {:select      true
                     :full-width  true
                     :SelectProps {:MenuProps    {:getContentAnchorEl nil}
                                   :render-value (fn [items]
                                               (if label-fn
                                                 (label-fn state lang)
                                                 (map identity items)))
                               :data-cy      data-cy}
                 :value       (or (value-fn state) "")
                 :on-change   (fn [e]
                                (let [selected (.. e -target -value)]
                                  (state-fn (first (filter #(= selected (value-fn %)) data)))))
                 :label       (i18n/translation label lang)
                 :disabled    disabled?}
                variant (assoc :variant variant))]
    [:> m/TextField props (map-indexed (partial menu-item value-fn label-fn1 state lang) data)]))))

I have the following piece of code to create a dropdown list with items that have a checkbox next to them. The problem is that the checkbox cannot be removed. When the user clicks on an already selected checkbox, nothing happens. And in this case, it should become deselect.

closed with the note: Solved

1 Answer

0 votes
selected by
Best answer

Don't know for absolute certain, but it seems that by passing :checked, you have made the checkbox component controlled - it will not react to anything apart from a change to that value, and you have to do that yourself by also providing an :on-change function and changing the underlying value.

Also note that you shouldn't be using sequential indices as React keys. Either don't use keys at all by avoiding lazy collections or figure out a natural key for components.

As a final note, IMO it's better to ask such specific support questions on the Clojurians Slack where we have multiple channels. For this case, there's #reagent. It's much easier to have an ongoing conversation there.