Search code examples
reactjsclojurescriptclojurescript-javascript-interopshadow-cljs

Import react-table into ClojureScript with Shadow-CLJS


Web development newbie here. I'm trying to use the NPM react-table package with a ClojureScript/Reagent project. I'm failing to import the package properly. What I've done:

1/installed react-table through NPM, it's in my project directory

2/in my main namespace, I've included (:require ["react-table" :as rt])

In the REPL I can see it's making some connection as just typing rt will return #js {:ReactTableDefaults #js {:data #js [], ...

How can I actually create a table? I've tried things such as

rt/ReactTable {:data [{:a 1 :b 2} {:a 3 :b 4} {:a 6 :b 8}] :columns [{:Header "a" :accessor "a"} {:Header "b" :accessor "b"}]} but I keep hitting into TypeError: module$node_modules$react_table$lib$index.ReactTable is not a function

I've also read https://code.thheller.com/blog/shadow-cljs/2017/11/10/js-dependencies-in-practice.html but that didn't help me enough.

Update - using figwheel I'm getting somewhere, and this is what I'd like to reproduce in shadow-cljs:

In project.clj: [cljsjs/react-table "6.8.6-0"]

In the "view" namespace: (:require [cljsjs.react-table] [reagent.core :as r])

Then this actually displays a table:

(def ReactTable (r/adapt-react-class (aget js/ReactTable "default")))
(defn test-table []
  [:div {:style {:width 320}}
  [ReactTable {:data    [{:a 1 :b 2} {:a 3 :b 6} {:a 6 :b 8}]
               :columns [
                     {:Header "a" :accessor "a" :width 200}
                     {:Header "b" :accessor "b" :width 100}]
           :showPagination false
           :defaultPageSize 3}]])

(defn main-panel []
  [test-table])

Thanks!


Solution

  • react-table uses a "default" export which you likely didn't use in the shadow-cljs build but sort of did in the cljsjs variant (ie. (aget js/ReactTable "default")).

    So the correct way to do this is:

    (ns your.app
      (:require ["react-table" :as rt :default ReactTable]))
    
    (defn test-table []
      [:div {:style {:width 320}}
        [:> ReactTable {:data ... :columns ...}]])
    

    The translation table in the docs might be a useful reference.