Search code examples
reactjsgoogle-chromegoogle-apigoogle-chrome-devtoolsnfc

Using Experimental Chrome API in React?


I am trying to use Chrome nfc api (WEB NFC) inside of react, so when you open the react page on mobile with nfc enabled and press a button it check to see if nfc scan.

I was reading through the doc and the sample code to do this is,

scanButton.addEventListener("click", async () => {
  log("User clicked scan button");

  try {
    const ndef = new NDEFReader();
    await ndef.scan();
    log("> Scan started");

    ndef.addEventListener("readingerror", () => {
      log("Argh! Cannot read data from the NFC tag. Try another one?");
    });

    ndef.addEventListener("reading", ({ message, serialNumber }) => {
      log(`> Serial Number: ${serialNumber}`);
      log(`> Records: (${message.records.length})`);
    });
  } catch (error) {
    log("Argh! " + error);
  }
});

My react page is currently,

import { Button } from "@material-ui/core";
import React from "react";

const nfcpage = () => {

  return (
    <>
      <Button
        id = "scanButton"
      >
          Press to test NFC
      </Button>
    </>
  );
};

export default nfcpage;

I want the scanButton code to run when the button is pressed. In other words to make scanButton into a function that can be called by my button via onClick{}.

Thank you


Solution

  • I was able to fix this by creating an async function from the sample code and passing that to onClick in the button component