How to include external JavaScript library in reactjs
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());
});
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;
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');