How to include external JavaScript library in reactjs
<p>I would like to know how it's possible to include an external JavaScript library in a react project. For example, I would like to import the jspdf library : https://github.com/MrRio/jsPDF/blob/master/jspdf.js and use it in my reactjs app.</p>
<p>So far I tried to use require like this : </p>
<pre><code>let React = require('react');
let { Spacing, Typography } = Styles;
let DoughnutChart = require(&quot;react-chartjs&quot;).Doughnut;
let Chart = require('react-google-charts').Chart;
let { StylePropable, StyleResizable } = Mixins;
let EditableDiv = require('../EditableDiv.jsx');
//some other library
//the library that matter for me
var pdfConverter = require('../utils/jspdf.source.js');

//then I have my classical react code which works and a function to generate ad pdf
_generatePdf: function(){
    console.log('Genrating pdf');
    var doc = new pdfConverter.jsPDF('p','pt');
    var img = new Image();
}
</code></pre>
<p>I have the following error : <strong>TypeError: pdfConverter.jsPDF is not a function</strong>.</p>
<p>To make it work, I made something ugly, I copy the source of jspdf-source.js into my react.jsx file and just call jsPDF instead of pdfConverter.jsPDF. It's definitely no the right way, but can't succeed to import and use the library.</p>
<p>Can you tell me what I'm doing wrong and how I can correct this?</p>
<p><strong>-EDIT-</strong></p>
<p>When I was using my ugly solution (copying the source into my file) I just had to do the following :</p>
<pre><code>var doc = new jsPDF('p','pt);
</code></pre>
<p>And it was working perfectly, expect that I had a very big file</p>
<p>After the suggested solution from @dannyjolie bellow, I've imported jspdf directly from the npm package, but I'm still not able to use the library. I tried the following code which lead to an error:</p>
<pre><code>var pdfConverter = require('jspdf');
var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');
</code></pre>
<p><strong>TypeError: pdfConverter is not a constructor</strong>
Meaning that I have to import the jsPDF coming from the package, not only jspdf?</p>
<p>Then I tried</p>
<pre><code>let pdfConverter = require('jspdf');
var converter = pdfConverter.jsPDF;
var doc = new converter('p', 'pt');
</code></pre>
<p><strong>ReferenceError: jsPDF is not defined</strong></p>
<p><strong>TypeError: converter is not a constructor</strong></p>
<p>Ok, obviously, I'm not importing the right thing or not the right way.
What I'm doing wrong?</p>