Search code examples
clojurescriptreagent

using React components in Reagent


I am trying to use components from http://react-components.com (eg. react-youtube) in Reagent based application, but probably my naive approach is not the right one. I tried to install NPM packages with lein-npm module, include script in html page and use them via reagent/adapt-react-class as in this SO question. But for except this sample I wasn't successful.

Usually I get errors like "require/import/module is not defined" or "Youtube is undefined" (by having (def yt-test [] (r/adapt-react-class js/Youtube)). I am confused about what is needed to do. I read something about webpack/browserify, saw cljsjs packages - are those required in order to make this working?


Solution

  • Those components are packaged as CommonJS modules. One approach for accessing CommonJS modules from ClojureScript is to bundle them into a single JavaScript file that can be included with your ClojureScript build.

    You'll need to create a JavaScript entry point file which requires your various NPM dependencies and exposes them to ClojureScript (for example, by setting them on window). Create a file (let's call it index.js) containing:

    window.YouTube = require('react-youtube');
    

    Then use a tool like Browserify to bundle your entry point file and all of the dependencies it requires:

    npm install -g browserify
    browserify index.js --standalone window > bundle.js
    

    Include bundle.js in your ClojureScript build and you'll be able to access the React component from ClojureScript via js/YouTube