Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include external JavaScript library in reactjs

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?

like image 882
FLCcrakers Avatar asked Mar 17 '16 16:03

FLCcrakers


People also ask

How use external library in react JS?

getElementById("externalLibrary")){ const script = document. createElement('script'); script.id='externalLibrary' script. type = 'text/javascript'; script. src = `https://externallibrary.com/example.js`; // Call some function from the library when it loads.

Where do I put JavaScript file in React?

React Hooks and other methods For features used across the application, we can simply add JS files to head using the <script> tag in our global index.


3 Answers

I know this is old, but I thought it would be helpful if someone posted a full working sample. It took me a while to figure this out, using this other post as a starting point:

How to make PDF from React?

Assuming you are using create-react-app, overwrite your App.js with the following below...

import React, { Component } from 'react';
import pdfConverter from 'jspdf';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
    this.toDataUrl = this.toDataUrl.bind(this);
  }

  toDataUrl(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
      var reader = new FileReader();
      reader.onloadend = function() {
        callback(reader.result);
      }
      reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
  }

  onClick() {
      var doc = new pdfConverter('p','pt','letter');
      //console.log(doc.getFontList() );
      this.toDataUrl('background.jpg', function(base64Img) {
        var imgData = base64Img;
        console.log(imgData);
        console.log('Adding to doc.');
        doc.addImage(imgData, 'JPEG', 0, 0, 612, 792);
        console.log('Image added.');
        doc.setFont('Times', 'Roman');
        doc.setFontSize(22);
        doc.text(20, 50, 'Park Entry Ticket');
        doc.setFontSize(16);
        doc.text(20, 80, 'Address1: ' );
        doc.text(20, 100, 'Address2: ' );
        doc.text(20, 120, 'Entry Date & time: ');
        doc.text(20, 140, 'Expiry date & time: ' );
        console.log('About to save');
        doc.save("test.pdf");
      });
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
            <input type='button'
        onClick={this.onClick} value="Print"/>
        </p>
      </div>
    );
  }
}

export default App;
like image 145
James Young Avatar answered Oct 19 '22 20:10

James Young


First of all, don't use the source file. Just npm install jspdf --save like any other package, and import it with var pdfConverter = require('jspdf');

Secondly, you're missing a () in this line var doc = new pdfConverter.jsPDF('p','pt');

Do something like this:

var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');
like image 29
dannyjolie Avatar answered Oct 19 '22 21:10

dannyjolie


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());
});
like image 12
Jason Kao Avatar answered Oct 19 '22 21:10

Jason Kao