Getting rc-slider to work with clojurescript and reagent

Intro

A slider and range component is good to have, as standard html only supports a single, horizontal slider, not min and max values and thus a selectable range on the same slider, see this discussion. The rc-slider is a mature react component that has been adapted to clojurescript via the cljsjs project. Unlike many other cljsjs projects it has also been recently updated (as of August 2021).

Installation

It's essential to have only one version of react in your project, ideally the latest one, as otherwise you will get exceptions due to webpack packages not being correctly consumed and errors relating to hooks, a recent addition to react.

So in your dependencies or dev-dependencies (like project.clj or ~/.lein/profiles.clj with lein):


:dependencies 
	[
	[cljsjs/react "17.0.2-0"]
	[cljsjs/react-dom "17.0.2-0"]
	[cljsjs/rc-slider "9.7.1-1" :exclusions [cljsjs/react cljsjs/react-dom]]
	]

In your clojurescript project (here we use re-frame, which of course is optional)

Here we create and use a Range react component which of course is hardly usable without tooltips.


(ns my.rc-slider
  (:require
   cljsjs.rc-slider
   [re-frame.core :as rf]
   [reagent.core :as reagent]
   ))
   
(def RcRange (reagent/adapt-react-class (.createSliderWithTooltip js/RcSlider js/RcSlider.Range)))

To just get a standard slider, e.g. a vertical slider:

(def RcSlider (reagent/adapt-react-class (.createSliderWithTooltip js/RcSlider js/RcSlider.default)))

Then we use the component as a reagent tag like so (see https://www.npmjs.com/package/rc-slider for configuration options):


[RcRange {:min 50 :max 100 :step 5 :dots true :default-value [70 80]
                   :on-change #(do (rf/dispatch [:set-value [:foo :min] (first %)])
                                   (rf/dispatch [:set-value [:foo :max (second %)]]))
                   :tip-formatter (fn [value] (str value " USD"))
                   :tip-props {:placement "bottom"}
                   }]

Problems with the rc-tooltip plugin will usually arise if you don't have a clean and recent react dependency in your project and some old react on your classpath. If you get it to work you have a mature, fast and flexible slider and range component for reagent.

Hope it helps.

Posted: 15 August 2021

comments powered by Disqus