How to include external JavaScript library in reactjs

FLCcrakers picture FLCcrakers · Mar 17, 2016 · Viewed 28.6k times · Source

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.

So far I tried to use require like this : 

let React = require('react');
let { Spacing, Typography } = Styles;
let DoughnutChart = require("react-chartjs").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();
}

I have the following error : TypeError: pdfConverter.jsPDF is not a function.

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.

Can you tell me what I'm doing wrong and how I can correct this?

-EDIT-

When I was using my ugly solution (copying the source into my file) I just had to do the following :

var doc = new jsPDF('p','pt);

And it was working perfectly, expect that I had a very big file

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:

var pdfConverter = require('jspdf');
var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');

TypeError: pdfConverter is not a constructor Meaning that I have to import the jsPDF coming from the package, not only jspdf?

Then I tried

let pdfConverter = require('jspdf');
var converter = pdfConverter.jsPDF;
var doc = new converter('p', 'pt');

ReferenceError: jsPDF is not defined

TypeError: converter is not a constructor

Ok, obviously, I'm not importing the right thing or not the right way. What I'm doing wrong?

Answer

Jason Kao picture Jason Kao · Jun 11, 2018

If you include the external js file link in your /public/index.html, you can use the external library with the window prefix.

Take JQuery as an example. Put the following line in your /public/index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Use it in your project like so:

window.$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});