React hooks and context provider for the Web Serial API
npm install react-web-serialReact hooks and context provider for the Web Serial API.
``bash`
npm install react-web-serial
- Serial Monitor — Minimal serial monitor app with an Arduino echo sketch
`tsx
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
Web Serial API is not supported in this browser.
; return (
{error &&
Error: {error.message}
}
const App = () => (
);
`
Context provider. Wrap your app or component tree with this.
`tsx`
#### 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 | Open port selection dialog and connect |disconnect
| | () => Promise | Close the port |write
| | (data: string \| Uint8Array) => Promise | Write data to the port |startSubscribe
| | () => void | Start reading data from the port |stopSubscribe
| | () => Promise | Stop reading data |clearReceivedData
| | () => void | Clear the received data buffer |
`ts
type SerialDataMode = "text" | "binary";
type SerialReceivedDataEntry =
| { mode: "text"; timestamp: Date; value: string }
| { mode: "binary"; timestamp: Date; value: Uint8Array };
``
Web Serial API is available in Chromium-based browsers (Chrome, Edge, Opera). See Can I use for details.
MIT