2017-07-16 21:02:13 +00:00
|
|
|
import QRCodeLib from 'qrcode';
|
2017-09-25 02:06:28 +00:00
|
|
|
import React from 'react';
|
2017-07-16 21:02:13 +00:00
|
|
|
|
|
|
|
// FIXME should store limited amount if history
|
|
|
|
// data -> qr cache
|
|
|
|
const cache: { [key: string]: string } = {};
|
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
interface Props {
|
|
|
|
data: string;
|
|
|
|
}
|
2017-07-16 21:02:13 +00:00
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
interface State {
|
|
|
|
qr?: string;
|
|
|
|
}
|
2017-07-16 21:02:13 +00:00
|
|
|
|
2018-01-29 19:13:46 +00:00
|
|
|
export default class QRCode extends React.PureComponent<Props, State> {
|
2017-09-25 03:29:49 +00:00
|
|
|
public state: State = {};
|
2018-05-11 02:34:27 +00:00
|
|
|
public UNSAFE_componentWillMount() {
|
2017-07-16 21:02:13 +00:00
|
|
|
// Start generating QR codes immediately
|
2017-09-25 02:06:28 +00:00
|
|
|
this.generateQrCode(this.props.data);
|
2017-07-16 21:02:13 +00:00
|
|
|
}
|
|
|
|
|
2018-05-11 02:34:27 +00:00
|
|
|
public UNSAFE_componentWillReceiveProps(nextProps: Props) {
|
2017-07-16 21:02:13 +00:00
|
|
|
// Regenerate QR codes if props change
|
|
|
|
if (nextProps.data !== this.props.data) {
|
2017-09-25 02:06:28 +00:00
|
|
|
this.generateQrCode(nextProps.data);
|
2017-07-16 21:02:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-25 02:06:28 +00:00
|
|
|
public render() {
|
|
|
|
const { qr } = this.state;
|
|
|
|
if (!qr) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return (
|
|
|
|
<img
|
|
|
|
src={qr}
|
2018-03-08 19:28:43 +00:00
|
|
|
alt="QR Code"
|
2017-09-25 02:06:28 +00:00
|
|
|
style={{
|
|
|
|
width: '100%',
|
|
|
|
height: '100%'
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
private generateQrCode(value: string) {
|
2017-07-16 21:02:13 +00:00
|
|
|
if (cache[value]) {
|
|
|
|
this.setState({ qr: cache[value] });
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
QRCodeLib.toDataURL(
|
|
|
|
value,
|
|
|
|
{
|
|
|
|
color: {
|
|
|
|
dark: '#000',
|
|
|
|
light: '#fff'
|
|
|
|
},
|
|
|
|
margin: 0,
|
|
|
|
errorCorrectionLevel: 'H'
|
|
|
|
},
|
|
|
|
(err, qr) => {
|
2017-09-25 02:06:28 +00:00
|
|
|
if (err) {
|
|
|
|
return;
|
|
|
|
}
|
2017-07-16 21:02:13 +00:00
|
|
|
cache[value] = qr;
|
|
|
|
this.setState({ qr });
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|