Skip to content

camiha/react-web-serial

Repository files navigation

react-web-serial

React hooks and context provider for the Web Serial API.

Install

npm install react-web-serial

Usage

Examples

  • Serial Monitor — Minimal serial monitor app with an Arduino echo sketch

Basic

import { SerialProvider, useSerialPort } from "react-web-serial";

const SerialMonitor = () => {
  const {
    isAvailableSerialApi,
    isConnected,
    isSubscribing,
    receivedData,
    error,
    connect,
    disconnect,
    write,
    startSubscribe,
    stopSubscribe,
    clearReceivedData,
  } = useSerialPort({
    options: { baudRate: 9600 },
  });

  if (!isAvailableSerialApi) {
    return <p>Web Serial API is not supported in this browser.</p>;
  }

  return (
    <div>
      <button onClick={connect} disabled={isConnected}>
        Connect
      </button>
      <button onClick={disconnect} disabled={!isConnected}>
        Disconnect
      </button>
      <button onClick={startSubscribe} disabled={!isConnected || isSubscribing}>
        Start Subscribe
      </button>
      <button onClick={stopSubscribe} disabled={!isSubscribing}>
        Stop Subscribe
      </button>
      <button onClick={() => write("hello")} disabled={!isConnected}>
        Send "hello"
      </button>
      <button onClick={clearReceivedData}>Clear</button>

      {error && <p>Error: {error.message}</p>}

      <ul>
        {receivedData.map((entry, i) => (
          <li key={i}>
            {entry.mode === "text" ? entry.value : Array.from(entry.value).join(", ")}
          </li>
        ))}
      </ul>
    </div>
  );
};

const App = () => (
  <SerialProvider>
    <SerialMonitor />
  </SerialProvider>
);

API

<SerialProvider>

Context provider. Wrap your app or component tree with this.

<SerialProvider>{children}</SerialProvider>

useSerialPort(params)

Parameters

Name Type Required Description
options SerialOptions Yes Options passed to port.open() (e.g. { baudRate: 9600 })
requestOptions SerialPortRequestOptions No Filters for navigator.serial.requestPort()
maxReceivedDataCount number No Max entries in receivedData buffer. Default: 1000
mode "text" | "binary" No Data mode for startSubscribe. Default: "text"

Return value

Name Type Description
isAvailableSerialApi boolean Whether the browser supports Web Serial API
port SerialPortInfo | null Connected port (exposes getInfo and forget)
isConnecting boolean Connection in progress
isConnected boolean Port is connected
isUserCancelled boolean User dismissed the port selection dialog
isSubscribing boolean Actively reading data from the port
receivedData SerialReceivedDataEntry[] Received data buffer
error Error | null Last error
connect () => Promise<void> Open port selection dialog and connect
disconnect () => Promise<void> Close the port
write (data: string | Uint8Array) => Promise<boolean> Write data to the port
startSubscribe () => void Start reading data from the port
stopSubscribe () => Promise<void> Stop reading data
clearReceivedData () => void Clear the received data buffer

Types

type SerialDataMode = "text" | "binary";

type SerialReceivedDataEntry =
  | { mode: "text"; timestamp: Date; value: string }
  | { mode: "binary"; timestamp: Date; value: Uint8Array };

Browser support

Web Serial API is available in Chromium-based browsers (Chrome, Edge, Opera). See Can I use for details.

License

MIT