Skip to content

Instantly share code, notes, and snippets.

@Jorger
Last active February 3, 2021 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jorger/ef60c8a87b9796019b838fb42296fee7 to your computer and use it in GitHub Desktop.
Save Jorger/ef60c8a87b9796019b838fb42296fee7 to your computer and use it in GitHub Desktop.
import "./styles.css";
import { decodeUrlLevel, validURL } from "../../utils/helpers";
import { useState } from "react";
import QrcodeDecoder from "qrcode-decoder";
import swal from "sweetalert";
const qr = new QrcodeDecoder();
const randomString = () => Math.random().toString(36);
const LoadFromQR = ({ label, handleQR }) => {
const [inputKey, setInputKey] = useState(randomString());
/**
* Para desplegar la acción de seleccionar la imagen de tipo QR
*/
const handleClick = () => {
const fileInput = document.querySelector("#fileInput");
if (fileInput) {
fileInput.click();
}
};
/**
* Función que recibe la imagen que el usuario a seleccionado
* @param {*} event
*/
const handleOnChange = async (event) => {
let isInvalidQR = true;
const image = URL.createObjectURL(event.target.files[0]);
const code = await qr.decodeFromImage(image);
if (code && code.data && validURL(code.data)) {
const url = code.data;
const pathname = new URL(url).pathname;
const dataURL = pathname.split("/");
if (dataURL.length === 3) {
const decodeLevel = decodeUrlLevel(dataURL[2]);
isInvalidQR = decodeLevel.error;
if (!isInvalidQR) {
handleQR && handleQR(decodeLevel.grid);
}
}
}
if (isInvalidQR) {
swal({
title: "Opps!",
text: "The QR code is invalid or was not created in the game",
icon: "error",
closeOnClickOutside: false,
closeOnEsc: false,
button: "Ok",
});
}
setInputKey(randomString());
};
return (
<>
<input
className="file-qr"
id="fileInput"
type="file"
accept="image/x-png"
onChange={handleOnChange}
key={inputKey}
/>
<button className="button file-qr-button" onClick={handleClick}>
{label}
</button>
</>
);
};
export default LoadFromQR;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment