Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
Jan Hamrský Avatar asked Feb 18 '16 18:02

Jan Hamrský


2 Answers

I wrote a step by step guide on how to achieve this with webpack: blob.tomerweller.com/reagent-import-react-components-from-npm

The general concept is the same as @scttnlsn suggested: bundle all npm packages in an external JS file and expose them through the global window object.

like image 103
Tomer Weller Avatar answered Nov 01 '22 02:11

Tomer Weller


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

like image 31
scttnlsn Avatar answered Nov 01 '22 00:11

scttnlsn